<pre name="code" class="java">
//输入一个数n,输出1~n的全排列
//形象化为把4个编号为1~n的小球放进编号1~n的箱子里
public class AllSort {
//假设此时n为4,0不算,若编号为n的小球放进箱子,相应的book[i]置1
static int book[]=new int[5];
//4个箱子里放的小球的编号,箱子编号1-4,0不算
static int a[]=new int[5];
//表示当前操作的箱子数,初始为1
static int count=0;
public static void dfs(int box) {
if (box==5) {
count++;
for (int i = 1; i < a.length; i++) {
if (i==a.length-1) {
System.out.println(a[i]);
}else {
System.out.print(a[i]);
}
}
}
for(int i=1;i<book.length;i++){
if(book[i]==0){
a[box]=i;
book[i]=1;
dfs(box+1);
book[i]=0;
}
}
}
public static void main(String[] args){
int
基于深度优先搜索的全排列实现方法
最新推荐文章于 2022-09-27 17:23:55 发布