题目描述:
给定两个整数 n 和 k,返回 1 … n 中所有可能的 k 个数的组合。
示例:
输入: n = 4, k = 2 输出: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]
思路:
代码:
class Solution {
public:
vector<vector<int>> combine(int n, int k) {
vector<vector<int>> ans;
vector<int> perm;
backtrack(0, ans, perm, n, k);
return ans;
}
void backtrack(int index, vector<vector<int>>& ans, vector<int>& perm,int n, int k){
if(index == k){
ans.push_back(perm);
return;
}
for(int i = 1; i <= n; ++i){
if(!perm.empty() && perm.back() >= i){
continue;
}
perm.push_back(i);
backtrack(index + 1, ans, perm, n, k);
perm.pop_back();
}
}
};
class Solution {
public:
vector<vector<int>> combine(int n, int k) {
if(n < 1 || k < 1) return {};
vector<vector<int>> ans;
vector<int> perm;
backtrack(1, ans, perm, n, k);
return ans;
}
void backtrack(int index, vector<vector<int>>& ans, vector<int>& perm,int n, int k){
if(perm.size() == k){
ans.push_back(perm);
return;
}
for(int i = index; i <= n; ++i){
perm.push_back(i);
backtrack(i + 1, ans, perm, n, k);
perm.pop_back();
}
}
};
|