[leetcode]526. Beautiful Arrangement
Analysis
心疼奶茶妹妹~—— [马云爸爸恐成最大赢家 哈哈哈]
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?
递归实现~
Implement
class Solution {
public:
int countArrangement(int N) {
res = 0;
visit.resize(N+1);
helper(N, 1);
return res;
}
void helper(int N, int index){
if(index == N+1){
res++;
return;
}
for(int i=1; i<=N; i++){
if(visit[i]==0 && (index%i==0 || i%index==0)){
visit[i] = 1;
helper(N, index+1);
visit[i] = 0;
}
}
}
private:
int res;
vector<int> visit;
};