77. Combinations

来源:互联网 发布:送礼物的淘宝店铺 编辑:程序博客网 时间:2024/05/20 00:35

Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

For example,
If n = 4 and k = 2, a solution is:

[  [2,4],  [3,4],  [2,3],  [1,2],  [1,3],  [1,4],]
程序如下所示:

class Solution {    public void backTracing(List<List<Integer>> llst, List<Integer> lst, int begin, int n, int k){        if (k == 0){            llst.add(new ArrayList<Integer>(lst));            return;        }        for (int i = begin; i <= n; ++ i){            lst.add(i);            backTracing(llst, lst, i + 1, n, k - 1);            lst.remove(lst.size() - 1);        }    }    public List<List<Integer>> combine(int n, int k) {        List<Integer> lst = new ArrayList<>();        List<List<Integer>> llst = new ArrayList<>();        backTracing(llst, lst, 1, n, k);        return llst;    }}



原创粉丝点击