public class test4 {
public static void f(char[] data, int k) {
for (int i = k; i < data.length; i++) {
//試探
{
char t = data[k];
data[k] = data[i];
data[i] = t;
}
f(data, k + 1);
//回溯(將改變形式的串,重回原樣)
{
char t = data[k];
data[k] = data[i];
data[i] = t;
}
}
//輸出
if (k==data.length) {
for (int i = 0; i < data.length; i++) {
System.out.print(data[i]+" ");
}
System.out.println();
}
}class
public static void main(String[] args) {
String a = "ABC";
char[] data = a.toCharArray();
f(data, 0);//從第一個字母開始排列
}
}
test