给定两个整数 n 和 k,返回范围 [1, n] 中所有可能的 k 个数的组合。
你可以按 任何顺序 返回答案。
示例 1:
输入:n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
示例 2:
输入:n = 1, k = 1
输出:[[1]]
提示:
1 <= n <= 20
1 <= k <= n
解题思路:
回溯 + 剪枝
if (len + n - pos + 1 < k) return; 剩余长度不足直接返回。
枚举每个值为起点的情况。
代码如下:
class Solution {
public:
vector<vector<int>> combine(int n, int k) {
vector<vector<int>>res;
int len = 0;
vector<int>path;
std::function<void(int pos)>helper = [&](int pos){
if (len + n - pos + 1 < k) return;
if (len == k) {
res.emplace_back(path);
return;
}
for (int i = pos; i <= n; ++i) {
path.emplace_back(i);
len++;
helper(i + 1);
len--;
path.pop_back();
}
};
helper(1);
return res;
}
};