题目地址:https://leetcode.com/problems/beautiful-arrangement/#/description
题目描述: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?
我的代码:
class Solution {
public:
int dfs(vector<vector<int>> &a,int* b,int k,int N){
int num=0;
for(int i=0;i<a[k].size();i++){
if(b[a[k][i]]==0){
b[a[k][i]]=1;
if(N==k) num++;
else num+=dfs(a,b,k+1,N);
b[a[k][i]]=0;
}
}
return num;
}
int countArrangement(int N) {
vector<vector<int>> a(N+1);
for(int i=1;i<=N;i++)
for(int j=i;j<=N;j++){
if(i==j) a[i].push_back(j);
else if(i%j==0||j%i==0){
a[i].push_back(j);
a[j].push_back(i);
}
}
int b[N+1];
for(int i=0;i<=N;i++) b[i]=0;
return dfs(a,b,1,N);
}
};
解题思路:
这是一个比较简单回溯算法,获得所有可行的情况,显然我们可以对所有n!种排列都做判断,但复杂度太高,有些情况对于第一个位置就已经不符合,这种做法很不合算。
于是我们先找出每个位置可以放的所有数,放在a中,即a[i]里面存放着所有满足整除i或者被i整除的数。然后对所有这些可能情况进行判断即可,数组b用来保存一个数是否已经放在了之前的位置,保证了数组是1到N的一个排列。