给定两个整数 n 和 k,返回 1 … n 中所有可能的 k 个数的组合。
示例:
输入: n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/combinations
解题思路
借助树的深度优先遍历思想, 用一个链表 path 来保存中间结果以及结果集 result
深度遍历算法中,用一个循环来表示树同一层的元素,然后递归表示不同层的元素
当 path 的大小已经等于 k,则加到结果集然后返回上一层
否则用一个循环遍历符合条件的元素,添加到 path,然后递归,递归时起点 + 1
符合条件 当前索引
<= n - 还需要选择的元素个数 + 1
则j <= n - (k - path.size()) + 1
返回时将path
最后元素弹出
代码
class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> result = new ArrayList<>();
Deque<Integer> path = new LinkedList<>();
dfs(n, k, 1, path, result);
return result;
}
private void dfs(int n, int k, int i, Deque<Integer> path, List<List<Integer>> result) {
if (path.size() == k) {
result.add(new ArrayList<>(path));
} else {
// 当前索引 <= n - 还需要选择的元素个数 + 1
for (int j = i; j <= n - (k - path.size()) + 1; j++) {
path.addLast(j);
dfs(n, k, j + 1, path, result);
path.removeLast();
}
}
}
}