[LeetCode] Beautiful Arrangement

526. Beautiful Arrangement

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.

  • new solution update 2022.03.07
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
int dp[1<<16];
int backTracking(int& n, int perm, int mask) {
if(perm == n + 1) {
return 1;
}
if(dp[mask]!=-1) return dp[mask];
dp[mask] = 0;
for(int i = 1; i <= n; i++) {
if(mask & (1<<i)) continue;
if(perm % i == 0 or i % perm == 0) {
dp[mask] += backTracking(n, perm + 1, mask | (1<<i));
}
}
return dp[mask];
}
public:
int countArrangement(int n) {
memset(dp,-1,sizeof(dp));
return backTracking(n, 1, 0);
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
vector<int> perm;
int sol(int n) {
if(!n) return 1;
int res(0);
for(int i = 0; i < n; i++) {
if(!(perm[i] % n) || !((n % perm[i]))) {
swap(perm[i], perm[n - 1]);
res += sol(n - 1);
swap(perm[i], perm[n - 1]);
}
}
return res;
}
public:
int countArrangement(int n) {
for(int i = 0; i < n; i++) perm.push_back(i + 1);
return n < 4 ? n : sol(n);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/29/PS/LeetCode/beautiful-arrangement/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.