Suppose you have N integers from 1 to N. We define a beautiful arrangement as an array that is constructed by these N numbers successfully if one of the following is true for the ith position (1 ≤ i ≤ N) in this array:
- The number at the ith position is divisible by i.
- i is divisible by the number at the ith position.
Now given N, how many beautiful arrangements can you construct?
本题定义了一个美丽排列,须满足排列中所有下标和下表对应的数能相互整除,给定一个从1到N的数组,求由这些数构成的美丽排列的个数。解题关键是通过交换任意两个位置的数穷举出n个数的全排列,然后判断符合条件的排列个数即是题目所求。
class Solution {
public:
int countArrangement(int N) {
vector<int> vs;
for(int i = 0; i < N; i++)
vs.push_back(i+1);
return count(N, vs);
}
int count(int n, vector<int> vs){
int res = 0;
if(n <= 0)
return 1;
for(int i =0; i < n; i++){
if(vs[i] % n == 0 || n % vs[i] == 0){
swap(vs[i], vs[n-1]);
res += count(n-1, vs);
swap(vs[n-1], vs[i]);
}
}
return res;
}
};