转自 博客地址
算法把列表分为两个列表,然后递归地把左边列表的项移到右边列表
初次使用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); //注意这里是创建了两个新的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>
省略了过程输出,最终结果输出如下:
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]