题目链接:526. 优美的排列(中等)
算法原理:
解法:DFS
Java代码:
java
class Solution {
//526. 优美的排列
//吴小哲写的跟我这个大差不差
int ret;
//int[] path;
boolean[] check;
public int countArrangement(int n) {
ret=0;
//path=new int[n+1];//是n+1而不是n
//for(int i=1;i<=n;i++) path[i-1]=i;
check=new boolean[n+1];//是n+1而不是n
dfs(n,1);//索引开始为1
return ret;
}
public void dfs(int n,int pos){
if(pos>n){ret++;return;}
for(int i=1;i<=n;i++){
if(!check[i]&&(i%pos==0||pos%i==0)){
//我们要保证每个数字只使用一次,而不是每个位置只使用一次
check[i]=true;//所以用i,check[i]=true表示i已经被使用了
//path[pos]=i;
dfs(n,pos+1);
check[i]=false;//恢复现场
}
}
// if(!check[pos]){
// for(int i=1;i<=n;i++){
// if(i%path[pos]==0||path[pos]%i==0){
// check[pos]=true;
// dfs(n,pos+1);
// check[pos]=false;
// }
// check[pos]=true;
// }
// }
}
}
