leetcode解题: Combinations (77)

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

For example,
If n = 4 and k = 2, a solution is:

1
2
3
4
5
6
7
8
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]

解法1: Backtracking

常规的backtracking的题目,这里的特殊点是每一次要更新还剩下需要挑选的数字的个数。 然后用另外一个变量pos记录当前已经探索到的数字的位置。

C++

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
34
class Solution {
public:
vector<vector<int>> combine(int n, int k) {
vector<vector<int>> res;
if (k <= 0 || n == 0) {
return res;
}
vector<int> cur;
helper(n, k, 1, cur, res);
return res;
}
void helper(int n, int k, int pos, vector<int>& cur, vector<vector<int>>& res) {
if (k == 0) {
res.push_back(cur);
return;
}
for (int i = pos; i <= n; ++i) {
cur.push_back(i);
helper(n, k - 1, i + 1, cur, res);
cur.pop_back();
}
return;
}
};

Java

1