Combinations

时间:2023-03-10 06:28:17
Combinations

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:

[
[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>> res;
if (k== || n==)
return res; for(int base=; base<=(n-k+); base++){
vector<int> tempres(,base);
helper(base,n,k-,tempres,res);
}
return res;
}
void helper(int base,int n, int num, vector<int>& tempres, vector<vector<int>>& res){
if(num==){
res.push_back(tempres);
return;
}
if(base+num->n){
return;
}
for(int i=base+; i<=n; i++){
tempres.push_back(i);
helper(i,n,num-,tempres,res);
tempres.pop_back();
}
}
};