526. Beautiful Arrangement
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?
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.
思路:这个题目的思路比较直接,生成全排列的过程中及时判断是够满足题目要求,及时剪枝就可以了。
1 bool isv(vector<int>&path, int a) 2 { 3 if (path.size() == 0) 4 return true; 5 return a % (path.size()+1) == 0 || (path.size()+1) % a == 0; 6 } 7 void getalla(vector<vector<int>>&r,vector<int>&arr, int now,vector<int>path) 8 { 9 if (now >= arr.size()) 10 { 11 r.push_back(path); 12 return; 13 } 14 for (int i = now; i <arr.size(); i++) 15 { 16 swap(arr[now], arr[i]); 17 if (isv(path, arr[now])) 18 { 19 path.push_back(arr[now]); 20 getalla(r, arr, now + 1, path); 21 path.pop_back(); 22 } 23 swap(arr[now], arr[i]); 24 } 25 } 26 int countArrangement(int N) 27 { 28 vector<vector<int>>r; 29 vector<int>arr,path; 30 for (int i = 0; i < N; i++) 31 arr.push_back(i + 1); 32 getalla(r, arr, 0, path); 33 return r.size(); 34 }