轉(zhuǎn)自 博客地址
算法把列表分為兩個列表埋凯,然后遞歸地把左邊列表的項移到右邊列表
初次使用Markdown点楼,排版十分猥瑣,請求原諒= .=
import java.util.*;
public class Test{
private static int NUM = 3;
static List<List<String>> finalResult=new ArrayList();
static void print(List l){
for(Object s:l){
System.out.print(s);
}
}
private static void sort(List datas, List target) {
if (target.size() == NUM) {
finalResult.add(target);
System.out.println();
return;
}
for (int i = 0; i < datas.size(); i++) {
List newDatas = new ArrayList(datas); //注意這里是創(chuàng)建了兩個新的List白对,原來的List將不會被操作修改
List newTarget = new ArrayList(target);
newTarget.add(newDatas.get(i));
newDatas.remove(i);
print(datas); //這兩個print的作用是輔助理解遞歸過程
System.out.print(" ");
print(target);
System.out.println();
sort(newDatas, newTarget);
}
}
public static void main(String[] args) {
String[] datas = new String[] { "a", "b", "c", "d" };
sort(Arrays.asList(datas), new ArrayList());
System.out.println("the Final Result:");
Iterator<List<String>> i=finalResult.iterator();
while(i.hasNext()){
System.out.println(i.next());
}
}
}
</code>
省略了過程輸出掠廓,最終結(jié)果輸出如下:
the Final Result:
[a, b, c] [a, b, d] [a, c, b] [a, c, d] [a, d, b]
[a, d, c] [b, a, c] [b, a, d] [b, c, a] [b, c, d]
[b, d, a] [b, d, c] [c, a, b] [c, a, d] [c, b, a]
[c, b, d] [c, d, a] [c, d, b] [d, a, b] [d, a, c]
[d, b, a] [d, b, c] [d, c, a] [d, c, b]