题目描述:
按照字典序输出自然数 1 到 n 所有不重复的排列,即 n 的全排列,要求所产生的任一数字序列中不允许出现重复的数字。
输入:n
输出:所有的排列情况
import java.io.*;
import java.util.*;
public class Main{
static int n;
static PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out));
public static void main(String[] args){
quickin in=new quickin();
n=in.nextInt();
int[] a = new int[n];
int[] b = new int[n];
dfs(0,a,b);
}
public static void dfs(int cur,int[] a,int[] b){
if(cur==n){
for(int i=0;i<n;i++){
pw.printf("%5d",a[i]);
}
pw.println();
pw.flush();
return;
}
for(int i=0;i<n;i++){
if(b[i]==0){
a[cur]=i+1;
b[i]=1;
dfs(cur+1,a,b);
b[i]=0;
}
}
}
}
class quickin{
BufferedReader br;
StringTokenizer st;
quickin(){
br = new BufferedReader(new InputStreamReader(System.in));
}
boolean hasNext(){
while(st==null||!st.hasMoreElements()){
try{
st=new StringTokenizer(br.readLine());
}catch(Exception e){
return false;
}
}
return true;
}
String next(){
if(hasNext()) return st.nextToken();
return null;
}
int nextInt(){
return Integer.parseInt(next());
}
}