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], ]
这个可以用深搜,在搜索过程中用vector保存中间结果,一旦满足条件就将其输出。
class Solution {
public:
vector<vector<int> > res;
vector<int> com;
void combine(int n, int k, int start)
{
if(k==0)
{
res.push_back(com);
return;
}
if(start>n) return;
com.push_back(start);
combine(n,k-1,start+1);
com.pop_back();
combine(n,k,start+1);
}
vector<vector<int> > combine(int n, int k) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
res.clear();
com.clear();
combine(n,k,1);
return res;
}
};