LeetCode-77-组合

给定两个整数 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],
]

Code

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
//time:O(n!)
//space:O(k)
class Solution {
public:
vector<vector<int>> combine(int n, int k) {
vector<vector<int>> res;
vector<int> temp;
//数字从1开始
DFS(1,res,temp,k,n);
return res;
}

void DFS(int index,vector<vector<int>>& res, vector<int>& temp,int k,int n){
//k表示剩下几位需要填充数字
if (k == 0) {
res.push_back(temp);
return;
}
//观察都为升序1-2、1-3、1-4这种,2-1这种被剪枝了,最小就从i开始
for (int i = index;i <= n;i++) {
temp.push_back(i);
DFS(i + 1, res, temp, k - 1, n);
temp.pop_back();
}
}
};

----\(˙<>˙)/----赞赏一下吧~