题目描述

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

示例:

1
2
3
4
5
6
7
8
9
10
输入: n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]

解法

1. DFS+回溯

思路:使用搜索+回溯来获取每一条路径

选择1之后,在2中就不能再选择1了,只能在[3, 4]中选择,防止重复情况的发生。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import java.util.List;
import java.util.ArrayList;
import java.util.Stack;

class Solution {
private List<List<Integer>> res;

public List<List<Integer>> combine(int n, int k) {
res = new ArrayList<>();
if (n <= 0 || k <= 0 || n < k) return res;
// 路径
Stack<Integer> path = new Stack<>();
dfs(1, path, n, k);
return res;
}

private void dfs(int start, Stack<Integer> path, int n, int k) {
// 终止条件
if (path.size() == k) {
res.add(new ArrayList<>(path));
return;
}
// 对当前数字以及后面数字进行遍历
for (int i = start; i <= n; i++) {
// 添加数字进入path
path.push(i);
// 只能添加比当前数字大的数字
dfs(i + 1, path, n, k);
// 退回
path.pop();
}
}
}

参考