1,题目要求
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的数字序列,对于其中任意的第i个数字,可以使得第i位的数字可以被i整除、或者i可以被第i个数字整除,就称这样的一个数字序列为beautiful。则一共有多少这样的序列?
2,题目思路
对于这道题,需要用到递归的办法。基本的思路就是每一位都进行判断,并定义一个used向量来记录已经使用过的数字。
一开始,pos从前往后进行遍历,这样会造成时间会非常大。因此,在pos的实际遍历中,是从后往前进行的,因为这样可以很快找到不满足条件的序列。
3,程序源码
class Solution {
public:
int countArrangement(int N) {
vector<bool> used (N+1, 0);
int res = 0;
helper(N, N, used, res);
return res;
}
void helper(int N, int pos, vector<bool>& used, int& res)
{
if(pos<=0) {
res++;
return;
}
else
{
for(int i = 1;i<=N;i++)
{
if(used[i] == 0 && ( i % pos == 0 || pos % i == 0))
{
used[i] = 1;
helper(N, pos-1, used, res);
used[i] = 0;
}
}
}
}
};