给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。
示例:
输入: n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
思路:
和全排列I一样,全排列是放到n为止,而这里只需放到k就可以停止
class Solution {
public:
void get(vector<vector<int>> &res, int k, vector<int> &temp, int n, int loc) {
if (temp.size() == k) {
res.push_back(temp);
return;
}
for (int i = loc; i < n; ++i) {
temp.push_back(i+1);
get(res, k, temp, n, i + 1);
temp.pop_back();
}
}
vector<vector<int>> combine(int n, int k) {
vector<vector<int>> res;
vector<int> temp;
get(res, k, temp, n, 0);
return res;
}
};