本文将给出一个使用
回溯法实现全排列的程序。
class="java">public class Permutations {
public void permute(String value, int startIndex, int endIndex) {
if (startIndex == endIndex) {
System.out.printf("%s\n", value);
} else {
for (int currIndex = startIndex; currIndex <= endIndex; currIndex++) {
value = swap(value, startIndex, currIndex);
permute(value, startIndex + 1, endIndex);
/** 回溯 */
value = swap(value, startIndex, currIndex);
}
}
}
private String swap(String value, int idxOne, int idxTwo) {
char[] charArray = value.toCharArray();
char temp = value.charAt(idxOne);
charArray[idxOne] = charArray[idxTwo];
charArray[idxTwo] = temp;
return new String(charArray);
}
}
测试程序如下:
public class Main {
public static void main(String[] args) {
String value = "ABCD";
new Permutations().permute(value, 0, value.length()-1);
}
}
运行结果:
ABCD
ABDC
ACBD
ACDB
ADCB
ADBC
BACD
BADC
BCAD
BCDA
BDCA
BDAC
CBAD
CBDA
CABD
CADB
CDAB
C
DBA
DBCA
DBAC
DCBA
DCAB
DACB
DABC