原题:
解决方法:
用dfs的方法来求解吧,leetcode很多题都是类似的方法。要注意的是dfs函数的返回条件以及循环中的处理逻辑。
代码:
Given two integers n and k, return all possible combinations ofk 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], ]
用dfs的方法来求解吧,leetcode很多题都是类似的方法。要注意的是dfs函数的返回条件以及循环中的处理逻辑。
代码:
void dfs(vector<vector<int>>& res, vector<int>& item, int start, int n, int k){
if (item.size() == k){
res.push_back(item);
return;
}
for(int i = start; i <= n; i++){
item.push_back(i);
dfs(res, item, i + 1, n, k);
item.pop_back();
}
}
vector<vector<int>> combine(int n, int k) {
vector<vector<int>> res;
vector<int> item;
dfs(res, item, 1, n, k);
return res;
}