package day0207;
import java.util.Scanner;
public class 全排列 {
static int [] box = null;
static int [] book = null;
static int n;
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
n = scan.nextInt();
box = new int[n+1];
book = new int[n+1];
dfs(1);
}
public static void dfs(int step) {
if(step==n+1) {
for (int i = 1; i < box.length; i++) {
System.out.print(box[i]+" ");
}
System.out.println();
return ;
}
for (int i = 1; i <= n; i++) {
if(book[i]==0) {//判定i是否已经用过
box[step] = i;
book[i] = 1;//i已经用过
dfs(step+1);
box[step] = 0;
book[i] = 0;//i没有用过
}
}
}
}
全排列Java
最新推荐文章于 2024-11-12 12:29:51 发布
本文介绍了如何使用Java编写一个全排列的深度优先搜索(DFS)程序,通过数组操作模拟书本排列问题,展示了递归函数在排列问题中的应用。
摘要由CSDN通过智能技术生成