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?
看到N不超过15心想是不是可以暴力一发,掏出计算器:fact(15)=1307674368000……看来需要优雅的暴力~
此题用递归可解,从第一个位置开始放数字,一直放到位置N。需要使用一个数组记录某个数字是否使用过,然后放之前判断合法性来剪枝。代码如下:
class Solution {
public:
void dfs(int pos, vector<bool> &vis, int N){
if (pos == N+1){
++ans;
}
for (int i = 1;i <= N;++i){
if (vis[i] == false && (i%pos==0 || pos%i==0)){
vis[i] = true;
dfs(pos+1, vis, N);
vis[i] = false;
}
}
}
int countArrangement(int N) {
vector<bool> vis(N, false);
ans = 0;
dfs(1, vis, N);
return ans;
}
private:
int ans;
};
这种做法复杂度为O(n!),跑下来100+ms。发现别人有10ms以内的算法:
class Solution {
public:
int countArrangement(int N) {
vector<int> vs;
for (int i = 0; i < N; ++i)
vs.push_back(i + 1);
return counts(N, vs);
}
private:
int counts(int n, vector<int>& vs) {
if (n <= 0)
return 1;
int ans = 0;
for (int i = 0; i < n; ++i) {
if (vs[i] % n == 0 || n % vs[i] == 0) {
swap(vs[i], vs[n - 1]);
ans += counts(n - 1, vs);
swap(vs[i], vs[n - 1]);
}
}
return ans;
}
};
也是使用递归解决,为什么效率差这么多呢?
在纸上演算了一下两种做法,发现做法一虽然进行了剪枝,但仍会产生大量无用的解空间。例如N=4时,(2,4,1,3)不是一个合法解,但在放到第四步之前做法一仍在尝试构造这个解。
做法二的巧妙之处在于从位置N向位置一放置数字。这种情况下,位置N只有【N的因子数】的情况;而如果从位置一开始,则有【N】种情况。其他位置也是这么个情况。因此倒着放会大大减少解空间。
弄明白这个后重写做法一如下:
class Solution {
public:
void dfs(int pos, vector<bool> &vis, int N){
++cnt;
if (pos == 0){
++ans;
}
for (int i = 1;i <= N;++i){
if (vis[i] == false && (i%pos==0 || pos%i==0)){
vis[i] = true;
dfs(pos-1, vis, N);
vis[i] = false;
}
}
}
int countArrangement(int N) {
vector<bool> vis(N, false);
ans = 0;
cnt = 0;
dfs(N, vis, N);
cout << cnt << endl;
return ans;
}
private:
int ans;
int cnt;
};
果然来到了10ms的级别。