问题描述:
给定两个整数 n 和 k,返回 1 … n 中所有可能的 k 个数的组合。
示例:
输入: n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/combinations
class Solution {
public:
void dfs(int i,int n,int k,vector<vector<int>> &res,vector<int> &tmp){
if(tmp.size()==k){
res.push_back(tmp);
return ;
}
for(int j=i;j<=n;j++){
tmp.push_back(j);
dfs(j+1,n,k,res,tmp);
tmp.pop_back();//回溯
}
}
vector<vector<int>> combine(int n, int k) {
vector<vector<int>> res;
vector<int> tmp;
dfs(1,n,k,res,tmp);
return res;
}
};