1.
桐桐的全排列
Description
今天,桐桐的老师布置了一道数学作业,要求列出所有从数字1到数字n的连续自然数的排列,要求所产生的任一数字
今天,桐桐的老师布置了一道数学作业,要求列出所有从数字1到数字n的连续自然数的排列,要求所产生的任一数字
序列中不允许出现重复的数字。因为排列数很多,桐桐害怕写漏了,所以她决定用计算机编程来解决。
Input
Input
只有一个整数n(1≤n≤9)。
Output
按字典序输出由1~n组成的所有不重复的数字序列,每行一个序列,每个数字之间有一个空格。
Sample Input
3
Sample Output
Sample Output
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
题解:DFS的一般理念设定一个数组visit[],作为判断当前是否已被遍历过。
代码:
import java.util.*;
public class 桐桐的全排列 {
static int n;
static int[] vis=new int[100];
static int[] a=new int[100];
public static void dfs(int k) {
if(k==n) {
for(int i=0;i<k;i++) {
if(i!=k-1)
System.out.print(a[i]+" ");
else
System.out.println(a[i]);
}
}
for(int i=0;i<n;i++) {
if(vis[i]==0) {
vis[i]=1;
a[k]=i+1;
dfs(k+1);
vis[i]=0;
}
}
}
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
n=in.nextInt();
for(int i=0;i<n;i++)
vis[i]=0;
dfs(0);
}
}