题目:
给定两个整数 n
和 k
,返回 1 ... n
中所有可能的 k
个数的组合。
示例 :
输入: n = 4, k = 2 输出: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]
思路:
这和79求子集几乎是没什么变动,无非是限定了子集长度,上一题掌握之后这一题信手捻来。
复杂度:
时间:O((n^2)。
空间:复杂度O(n)。
代码:
List<List<Integer>> list;
public List<List<Integer>> combine(int n, int k) {
list = new ArrayList<>();
dfs(n,new ArrayList<Integer>(),k);
return list;
}
void dfs(int n,ArrayList list2,int count){
//减少无意义的资源浪费
if(n+list2.size()<count) return;
if(list2.size()==count){
list.add(new ArrayList<Integer>(list2));
return ;
}
for(int i=n;i>0;i--){
list2.add(i);
dfs(i-1,list2,count);
list2.remove(list2.size()-1);
}
}