combinations(组合)

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],
]

从1,。。。,n中选出k个数组成集合。

这题和  组合的和combinations sum全排列  类似

这一题跟全排列有点像,但是又不太像,不能混淆。全排列是所有数字(字母)参与排列,这里只是一部分数字参与排列。跟combinations sum很像,是差不多的原理。
在全排列中,1,2,3和3,2,1是不同的两个排列,这里算是一个。
所以,这里需要注意点:1、当list长度=k的时候,表示满足一个要求。2、每次遍历时,从剩下的元素中找元素,并不是从头开始。

class Solution {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> res=new ArrayList<List<Integer>>();
        if(k<=0) return res;
        helper(res,n,k,new ArrayList<Integer>(),1);
        return res;
    }
    public void helper(List<List<Integer>> res,int n,int k,List<Integer> list,int index){
        if(list.size()==k){
            res.add(new ArrayList<Integer>(list));
            return ;
        }
        
        for(int i=index;i<=n;i++){
             
            list.add(i);
            helper(res,n,k,list,i+1);
            list.remove(list.size()-1);
        }
    }
}
原文地址:https://www.cnblogs.com/xiaolovewei/p/8179522.html