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],
]
这道题感觉跟Subsets II有一点相似,都是通过回溯来按位生成题解。
本来想用一个visit数组记录每一个数字出现的情况,但因为这一题1~n是严格递增的,所以并没有必要。
class Solution {
public:
//int visited[10000] = {0};
void f(int step,int n,int k,vector<int> &res,vector<vector<int>> &ans){
if(res.size() == k){
ans.push_back(res);
return ;
}
for(int i = step;i <= n;i++){
res.push_back(i);
f(i+1,n,k,res,ans);
res.pop_back();
}
}
vector<vector<int> > combine(int n, int k) {
vector<vector<int>> ans;
vector<int> res;
f(1,n,k,res,ans);
return ans;
}
};
原文地址:http://blog.csdn.net/iboxty/article/details/45055389