日期:2014-05-20 浏览次数:20943 次
public class Permutation {
public static void main(String[] args) {
Character[] ps = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L'};
long timer = System.currentTimeMillis();
int total = 0;
total = fastPermutation(ps, 0);
System.out.println("Got " + total + "\tspend: " + (System.currentTimeMillis() - timer) + "ms");
}
public static int fastPermutation(Character[] ps, int pos) {
int cnt = 0;
if (pos < ps.length - 1) {
fastPermutation(ps, pos + 1);
for (int i = pos + 1; i < ps.length; i++) {
swap(ps, pos, i);
cnt += fastPermutation(ps, pos + 1);
swap(ps, pos, i);
}
} else {
cnt++;
//System.out.println(Arrays.toString(ps)); // 打开输出的话,会比较浪费时间。
}
return cnt;
}
private static void swap(Character[] ps, int pa, int pb) {
Character tmp = ps[pa];
ps[pa] = ps[pb];
ps[pb] = tmp;
}
------解决方案--------------------
写了个深搜。
暴力出所有情况。
但是,这是最不效率的方法。
应该有很高效的算法。
public class Rank {
private char[] rank;
private boolean[] vist;
private char[] c;
private int size;
public Rank(char[] c){
rank = new char[c.length];
vist = new boolean[c.length];
this.c = c;
size = c.length;
}
public void showAllRank() {
for (int i = 0; i < size; i++) {
vist[i] = false;
}
dfs(0);
}
public void dfs(int level) {
if (level == size) {
for (int i = 0; i < size; i++) {
System.out.print(rank[i]);
}
System.out.println();
} else {
for (int i = 0; i < size; i++) {
if ( !vist[i]) {
vist[i] = true;
rank[level] = c[i];
dfs(level+1);
vist[i] = false; //回溯
}
}
}
}
}