算法是这样的,如果给定N个不同字符,将这N个字符全排列,最终的结果将会是N!种。如:给定 A、B、C三个不同的字符,则结果为:ABC、ACB、BAC、BCA、CAB、CBA一共3!=3*2=6种情况。
import java.util.*;
public class charSort {
public static long cnt = 0;
public static void fullPermutation(Vector<Character> sourse, Vector<Character> result) {
if(sourse.size() == 0) {
for(int i = 0; i < result.size(); i++)
{
System.out.print(result.elementAt(i));
}
System.out.print("\n");
cnt++;
return ;
}
for(int i = 0; i < sourse.size(); i++)
{
Vector<Character> tSourse = new Vector<Character>(sourse);
Vector<Character> tResult = new Vector<Character>(result);
tResult.add(sourse.elementAt(i));
tSourse.remove(i);
fullPermutation(tSourse, tResult);
}
}
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
int N = cin.nextInt();
Vector<Character> sourse = new Vector<Character>();
Vector<Character> result = new Vector<Character>();
for(int i = 0; i < N; i++)
{
sourse.add((char)('A' + i));
}
fullPermutation(sourse, result);
System.out.println(cnt);
}
}
类似于阶乘的递归输出