给出一个数字n,求出所有的全排列,如给出3则结果为:
3210
2310
2130
2103
3120
1320
1230
1203
3102
1302
1032
1023
3201
2301
2031
2013
3021
0321
0231
0213
3012
0312
0132
0123
代码如下:
3210
2310
2130
2103
3120
1320
1230
1203
3102
1302
1032
1023
3201
2301
2031
2013
3021
0321
0231
0213
3012
0312
0132
0123
代码如下:
import java.util.*;
import java.io.*;
public class P1 {
public static void main( String[] args ); {
try {
BufferedReader in = new BufferedReader( new InputStreamReader( System.in ); );;
System.out.println("Enter the number:");;
String input = in.readLine();;
int inputInt = Integer.parseInt( input );;
P1 p = new P1();;
LinkedList< String > a = new LinkedList< String >();;
while( inputInt != -1 ); {
a = p.convert( inputInt );;
System.out.println("The Result is:");;
for( int i = 0;i < a.size();;i++ ); {
System.out.println( a.get( i ););;
}
System.out.println("contain " + a.size(); + " numbers!" );;
System.out.println("Enter the number:");;
input = in.readLine();;
inputInt = Integer.parseInt( input );;
}
}catch( Exception e ); {
e.printStackTrace();;
}
}
public LinkedList<String> convert( int n ); {
LinkedList< String > temp = new LinkedList< String >();;
LinkedList< String > result = new LinkedList< String >();;
if( n == 0 ); {
result.add( "0" );;
return result;
}
if( n < 0 ); {
System.out.println("error!!");;
return temp;
}
temp = convert( n - 1 );;
String tempStr = new String();;
StringBuffer tempSB = new StringBuffer();;
for( int i = 0;i < temp.size();;i++ ); {
tempStr = temp.get( i );;
//System.out.println( "TEST1:" + tempStr );;
tempSB = new StringBuffer( tempStr );;
for(int j = 0;j < n + 1;j++ ); {
tempStr = new String( tempSB.insert(j,n); );;
result.add( tempStr );;
tempSB.deleteCharAt( j );;
//System.out.println( "TEST2:" + tempStr );;
}
}
return result;
}
}