列出所有组合的算法

实现combinations( List<Integer> data, int n) n==2,当n变的更大的时候

解释:从[1,2,3,4]中取出两个数方法名为combinations( List<Integer> data, int n);

看到这个题目作为一个小白第一下思考的就是使用循环,但是如果出现n的数目改变的时候,我们只能添加for循环实现。

这个给出的是使用递归的方法,希望有大佬一起探讨。
下面是代码

public class Combinations {
    public void combinations(List<Integer> selected, List<Integer> data, int n) {
        //initial value for recursion
        //how to select elements
        //how to output
        if (n == 0) {
            for (Integer i : selected) {
                System.out.print(i);
                System.out.print(" ");
            }
            System.out.println();
            return;
        }
        if (data.isEmpty()) return;

        //select element 0
        selected.add(data.get(0));//将第一个值添加上去
        combinations(selected, data.subList(1, data.size()), n - 1);
        //un-select element 0

        selected.remove(selected.size() - 1);
        combinations(selected, data.subList(1, data.size()), n);
    }
    public static void main(String[] args) {
        Combinations combinations = new Combinations();
        combinations.combinations(new ArrayList<Integer>(), Arrays.asList(1, 2, 3,4,5,6), 4);
    }
}

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,314评论 19 139
  • 他——一个普通的农村人,南方那边的,人老了,除了那么点文化,就只剩下聊聊天,卤卤菜的工夫了。一生也没经历过什么大事...
    傲慢与偏见612阅读 191评论 0 2
  • 其实这篇日志真不知该如何开始,既然如此就这样草草作个开头好了。 我记得四年前的这个时间,我写下了大学以来的第一篇东...
    毅如往昔Evan阅读 469评论 0 0
  • 四月中旬的风,温暖而不激烈,似乎要把人从外到内都吹的透彻,像夏日却也没有夏天的炎热,像秋天却也没有秋风的萧瑟和微凉...
    牛小蜗阅读 218评论 1 2
  • 那天,天很蓝,刚好你从身边走过,我很想开口跟你打个招呼,可是…… 我依然是胆小的,感觉那么不一样的你,我只是想象走...
    离见秋阅读 256评论 3 3

友情链接更多精彩内容