做了第三题-搭积木和 第六题-寒假作业,都用了全排列。
用dfs写全排列:
/*比如从1-9,思路:让a[1]-a[9]每个数从1-9遍历,用visit[10]
*记录,如果用过了,置为false.*/
package test;
public class Main {
static int count = 0;
public static void main(String[] args) {
int a[] = new int[10];
boolean visit[] = new boolean[10];
dfs(a,visit,1);
System.out.println(count);
}
private static void dfs(int[] a, boolean[] visit, int num) {
if (num==10) {
count++;
return;
}
for (a[num] = 1; a[num] <= 9; a[num]++) {
if (judge(a)) {//这里根据情况剪枝,减少计算量
if (visit[a[num]]==false) {
visit[a[num]]=true;
num = num + 1;
dfs(a, visit, num);
num = num -1;
visit[a[num]]=false;
}
}else {
continue;
}
}
}
private static boolean judge(int[] a) {
return true;
}
}
在网上又查到了效率高一点的全排列算法
package test;
public class Main {
static int count = 0;
/**
* @param args
*/
public static void main(String[] args) {
int a[] = new int[10];
for (int i = 0; i < a.length; i++) {
a[i] = i;
}
permulation(a, 0, a.length);
System.out.println(count);
}
public static void permulation(int[] list, int start, int length ) {
int i;
if (start == length) {
if (juedje(list)) {//判断
count +=1;
}
} else {
for (i = start; i < length; i++) {
swap(list, start, i);
permulation(list, start + 1, length);
swap(list, start, i);
}
}
}
private static boolean juedje(int[] list) {
return true;
}
public static void swap(int[] list, int start, int i) {
int temp;
temp = list[start];
list[start] = list[i];
list[i] = temp;
}
}