uppose 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?
Example 1:
Input: 2
Output: 2
Explanation:
The first beautiful arrangement is [1, 2]:
Number at the 1st position (i=1) is 1, and 1 is divisible by i (i=1).
Number at the 2nd position (i=2) is 2, and 2 is divisible by i (i=2).
The second beautiful arrangement is [2, 1]:
Number at the 1st position (i=1) is 2, and 2 is divisible by i (i=1).
Number at the 2nd position (i=2) is 1, and i (i=2) is divisible by 1.
Note:
- N is a positive integer and will not exceed 15.
Runtime: 168 ms, faster than 18.79% of C++ online submissions for Beautiful Arrangement.
自己的解法就是暴力搜索。
#include <vector>
#include <set>
#include <iostream>
using namespace std;
class Solution {
public:
int countArrangement(int N) {
vector<bool> visited(N,false);
int ret = ;
helper(visited, ret, );
return ret;
}
void helper(vector<bool>& visited, int& ret, int idx){
if(idx == visited.size()){
ret++;
return;
}
for(int i=; i < visited.size(); i++){
if(!visited[i] && ((i+) % (idx+) == || (idx+) % (i+) == )){
visited[i] = true;
helper(visited, ret, idx+);
visited[i] = false;
}
}
}
};
看一个比较巧妙的,把每一个数和最后一个index对比,如果满足条件,就把n-1的情况加到结果中,因为这相当于在n-1的结果中加入了后一项,长度增加1,但是数量还是n-1的数量,所以可以直接加
到结果中,但是这里的helper需要带nums,因为交换以后的nums不是1-n了。
class Solution {
//generate all permutaitons swapping from the back and check if valid
private:
int helper(int n, vector<int>& nums){ //checking index == n
if (n <= ){ //a single num is always valid
return ;
}
int res = ;
for (int i = n-; i >= ; i--){
if (nums[i] % n == || n % nums[i] == ){
swap(nums[i], nums[n-]);
res += helper(n-, nums);
swap(nums[i], nums[n-]);
}
}
return res;
}
public:
int countArrangement(int N) {
vector<int> nums;
for (int i = ; i <= N; i++){
nums.push_back(i);
}
return helper(N, nums);
}
};