题目:
给定两个整数 n 和 k,返回范围 [1, n] 中所有可能的 k 个数的组合。
你可以按 任何顺序 返回答案。
示例1:
输入:n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
示例2:
输入:n = 1, k = 1
输出:[[1]]
提示:
1 <= n <= 20
1 <= k <= n
解题代码:
class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> res = new ArrayList<>();
Deque<Integer> path = new ArrayDeque<Integer>();
int depth = 0;
int index = 1;
dfs(res, path, n, k, depth, index);
return res;
}
public void dfs(List<List<Integer>> res, Deque<Integer> path, int n, int k, int depth, int index){
// depth == k 说明数组已经满足了k个数
if(depth == k){
res.add(new ArrayList<>(path));
return;
}
for(int i = index; i < n + 1; i++){
path.addLast(i);
dfs(res, path, n, k, depth + 1, i+1);
path.removeLast();
}
}
}