Friday, October 11, 2013

Combinations [Leetcode]

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],
]
Solution: to generate the combination with k numbers and avoid making the duplicates, we always append the larger number at the end of each of the combinations with k-1 numbers, e.g, we has a combination with k-1 numbers, C, we only append the number greater than c[k-1] at the end of C to generate C' with k numbers.

class Solution {
public:
    vector<vector<int> > combination(int n, int k){
        vector<vector<int> > ret, subRet;
        if(k==0) { 
            vector<int> r; ret.push_back(r); return ret;  
        } 
        subRet = combination(n, k-1);
        for(int i=0; i<subRet.size(); ++i){
            int tmp=0;
            if(!subRet[i].empty())
                tmp = subRet[i].back();
            for( int j=tmp+1; j<=n; j++){
                subRet[i].push_back(j);
                ret.push_back(subRet[i]);
                subRet[i].pop_back();
            }
        }
        return ret;
    }
    vector<vector<int> > combine(int n, int k) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        vector<vector<int> > ret;
        if(k<=0 || n<=0 || k>n)
            return ret;
        ret = combination(n, k);
        return ret;
    }
};

No comments:

Post a Comment