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], ]
#include<vector>
using std::vector;
class Solution
{
public:
vector<vector<int> > combine(int n, int k)
{
vector<vector<int>> res;
vector<int> temp(k,0);
get_res(0,0,k,n,res,temp);
return res;
}
void get_res(int data,int now, int k, int n, vector<vector<int>>& res, vector<int>& temp)
{
if(k == now)
{
res.push_back(temp);
return;
}
for(int i = data+1; i <= n-k+now+1; i++)
{
temp[now] = i;
get_res(i,now+1,k,n,res,temp);
}
return;
}
};原文:http://blog.csdn.net/shaya118/article/details/42661003