-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathBeautiful Arrangement.cpp
46 lines (34 loc) · 1.12 KB
/
Beautiful Arrangement.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/*
Solution by Rahul Surana
***********************************************************
Suppose you have n integers labeled 1 through n. A permutation of those n integers perm
(1-indexed) is considered a beautiful arrangement if for every i (1 <= i <= n), either of the following is true:
perm[i] is divisible by i.
i is divisible by perm[i].
Given an integer n, return the number of the beautiful arrangements that you can construct.
***********************************************************
*/
class Solution {
public:
vector<int> dp;
int countArrangement(int n) {
// int dp[15];
dp.resize((1<<(n+1)),-1);
int count = f(n,0,1);
return count;
}
int f(int n, int x, int k){
if(k > n){
return 1;
}
if(dp[x] != -1) return dp[x];
int ans = 0;
for(int i = 1; i <= n; i++){
if(!(x&(1<<(i-1))) && (i % k ==0 || k%i == 0 )){
int m = x | (1<<(i-1));
ans += f(n,m,k+1);
}
}
return dp[x] = ans;
}
};