Monday, November 25, 2013

LeetCode Problem : Combinations

Problem


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],
]

Code


void c_r(int j,int k,int pos,int n,vector<int>& out,vector<vector<int> >& result)
{
    if(k == 0){
        result.push_back(vector<int>(out.begin(),out.end()));
        return;
    }
    for(int i = j;i <= n - k + 1;++i){
        out[pos] = i;
        c_r(i + 1,k - 1,pos + 1,n,out,result);
    }
}
vector<vector<int> > combine(int n, int k) {
    // IMPORTANT: Please reset any member data you declared, as
    // the same Solution instance will be reused for each test case.
    vector<int> out(k);
    vector<vector<int> > result;
    c_r(1,k,0,n,out,result);
    return result;
}

No comments:

Post a Comment