给定两个整数 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

相关文章:

  • 2022-02-08
  • 2021-09-30
  • 2022-12-23
  • 2022-01-04
  • 2022-12-23
  • 2022-01-03
  • 2021-10-01
  • 2022-12-23
猜你喜欢
  • 2021-07-05
  • 2021-07-14
  • 2022-02-08
  • 2021-11-17
  • 2022-01-27
  • 2021-08-17
  • 2022-12-23
相关资源
相似解决方案