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], ]Backtracking
思路:回溯法
class Solution {
public:
vector<vector<int>> res;
void function(int pos,int n,int k,vector<int> v)
{
if(v.size()==k)//当vector容器中有k个元素时,将v插入到res中
res.push_back(v);
else{
for(int i=pos;i<=n;i++)
{
vector<int> temp(v);
temp.push_back(i);
function(i+1,n,k,temp);
}
}
}
vector<vector<int> > combine(int n, int k) {
if(n<=0||k<=0||k>n)
return res;
vector<int> v;
function(1,n,k,v);
return res;
}
};