【DFS】LeetCode 526. 优美的排列
题目链接
思路
与【DFS】LeetCode 46. 全排列思路类似。
代码
class Solution {
private int result = 0;
private boolean[] used;
public int countArrangement(int n) {
used = new boolean[n + 1];
dfs(1, n);
return result;
}
void dfs(int currentPos, int n){
if(currentPos > n){
result++;
return;
}
for(int i = 1; i <= n; i++){
if((i % currentPos == 0 || currentPos % i == 0) && !used[i]){
used[i] = true;
dfs(currentPos + 1, n);
used[i] = false;
}
}
}
}