Tuesday, February 11, 2014

[leetcode][**] Combinations

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],
]
My Code:

 void bfs(int start,int end, int k, vector<int> &current, vector<vector<int> > &res){
        if(end - start + 1 < k) return;
        if(k == 0){
            res.push_back(current);
            return;
        }
        for(int i = start; i <= end; ++i){
            current.push_back(i);
            bfs(i+1, end, k-1, current, res);
            current.pop_back();
        }
    }
    vector<vector<int> > combine(int n, int k) {
        vector<vector<int>> res;
        if(n < k) return res;
        vector<int> current;
        bfs(1, n, k, current, res);
        return res;
    }

No comments:

Post a Comment