列出所有组合的算法

2018-05-16  本文已影响0人  liust15

实现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);
    }
}

上一篇 下一篇

猜你喜欢

热点阅读