全排序的递归算法

转自 博客地址

算法把列表分为两个列表,然后递归地把左边列表的项移到右边列表
初次使用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]

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,934评论 0 23
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,981评论 19 139
  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 6,537评论 0 17
  • 我们班的第一次劳动课。 “老师,我们终于搞完了!” “啊!你们太棒了!” “耶!” “你们太伟大了,我爱你们!” ...
    瑶瑶啊阅读 405评论 0 0
  • 刚踏入树木园的时候,看到的是幽长的小路和丛生的草木。由于已是深秋,路面铺满薄薄的一层落叶。走进这样的林子,不仅...
    荏苒几盈虚阅读 288评论 0 0