077 Combinations 组合

给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。
例如,
如果 n = 4 和 k = 2,组合如下:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]
详见:https://leetcode.com/problems/combinations/description/

Java实现:

class Solution {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> res=new ArrayList<List<Integer>>();
        List<Integer> out=new ArrayList<Integer>();
        helper(n,k,1,out,res);
        return res;
    }
    private void helper(int n,int k,int start,List<Integer> out,List<List<Integer>> res){
        if(out.size()==k){
            res.add(new ArrayList<Integer>(out));
        }
        for(int i=start;i<=n;++i){
            out.add(i);
            helper(n,k,i+1,out,res);
            out.remove(out.size()-1);
        }
    }
}

参考:http://www.cnblogs.com/grandyang/p/4332522.html

posted on 2018-04-03 21:52  lina2014  阅读(95)  评论(0编辑  收藏  举报

导航