leetcode(77) combinations 解法

Given two integers n and k, return all possible combinations of k numbers out of 1 … n.

Example:

1
2
3
4
5
6
7
8
9
10
Input: n = 4, k = 2
Output:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]

解法

典型的深度优先搜索题,采用递归写就好了,start标记从start开始向后做选择,当搜索完成helper返回后注意回溯。

具体代码如下:

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
class  {
List<List<Integer>> res = new ArrayList<>();
List<Integer> tmp = new ArrayList<>();

public List<List<Integer>> combine(int n, int k) {
helper(n, k, 1);
return res;
}

void helper(int n, int k, int start) {
if (tmp.size() == k) {
List<Integer> a = new ArrayList<>();
for (int i = 0; i < tmp.size(); i++) {
a.add(tmp.get(i));
}
res.add(a);
return;
}
for (int i = start; i <= n; i++) {
tmp.add(i);
helper(n, k, i + 1);
tmp.remove((Integer) i);
}
}
}