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], ]
和491相似。
public class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> res=new ArrayList<>();
ArrayList<Integer> list=new ArrayList<>();
helper(n,res,list,k,1);
return res;
}
public void helper(int n, List<List<Integer>> res, ArrayList<Integer> list, int k, int index){
if(list.size()==k){
res.add(new ArrayList<Integer>(list));
return;
}
for(int i=index;i<=n;i++){
list.add(i);
helper(n,res,list,k,i+1);
list.remove(list.size()-1);
}
}
}