leetcode77. 组合

题目

给定两个整数 n 和 k,返回 1 … n 中所有可能的 k 个数的组合。

示例:

输入: n = 4, k = 2
输出: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]

解题思路

类似之前做过的全排列,思路是一样的,只是不需要从头遍历,直接往下走,深度遍历即可。

代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> res = new ArrayList<>();
dfs(res, new ArrayList<Integer>(), n, 1, k);
return res;
}
public void dfs(List<List<Integer>> res, List<Integer> list, int n, int index, int k) {
if(list.size() == k) {
res.add(new ArrayList<>(list));
return ;
}
for(int i = index; i <= n - (k-list.size()) + 1; i ++) {
list.add(i);
dfs(res, list, n, i+1, k);
list.remove(list.size()-1);
}
}
}

提交结果

成功
显示详情
执行用时 : 6 ms, 在Combinations的Java提交中击败了85.95% 的用户
内存消耗 : 49.8 MB, 在Combinations的Java提交中击败了56.03% 的用户