Java 求全排列的两种方式

来源:互联网 发布:人工蜂群算法流程图 编辑:程序博客网 时间:2024/05/21 00:54

1 邻为互换法:

public class FullSort2 {


/*
* isExist判断j位置的字符是否已经在list[0]~list[j-1]中出现过了
* list是含重复字符的数组,i是指示当前位置的游标,j是要判断的字符的位置
*/
static boolean isExist(char a[], int k, int i) {
for (int j = k; j < i; j++) {
if (a[j] == a[i]) {
return true;
}
}
return false;
}


static void full(char[] a, int k) {
if (k == a.length - 1) {
show(a);
return;
}
for (int i = k; i < a.length; i++) {
if (isExist(a, k, i)) {
continue;
}
exch(a, i, k);
full(a, k + 1);
exch(a, i, k);
}
}


static void show(char[] a) {
for (int i = 0; i < a.length; i++)
System.out.print(a[i] + " ");
System.out.println();
}


public static void main(String[] args) {
char[] a = "ACC".toCharArray();
full(a, 0);
}


static void exch(char[] a, int i, int j) {
char swap = a[i];
a[i] = a[j];
a[j] = swap;
}

}


2 回溯法:


public class Permutation2 {
public static ArrayList<String> Permutation(String str) {
ArrayList<String> result = new ArrayList<String>();
if (str == null || str.length() == 0) {
return result;
}


char[] chars = str.toCharArray();
boolean[] used = new boolean[str.length()];
helper(chars, used, new StringBuffer(), result);
return result;
}


private static void helper(char[] chars, boolean[] used, StringBuffer sub, ArrayList<String> result) {
if (sub.length() == chars.length) {
result.add(sub.toString());
return;
}
for (int i = 0; i < used.length; i++) {
if (used[i] || i > 0 && !used[i - 1] && chars[i] == chars[i - 1]) {
continue;
}
sub.append(chars[i]);
used[i] = true;
helper(chars, used, sub, result);
sub.deleteCharAt(sub.length() - 1);
used[i] = false;
}
}


public static void main(String[] args) {
String string = "abc";
ArrayList<String> list = Permutation(string);
for (String str : list) {
System.out.println(str);
}
}
}



0 0
原创粉丝点击