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

典型暴力搜索题,一共有n种可能,对于每个元素i,即可以放入结果中,又可以不放入结果中,
注意搜索时剪枝,即每种结果有k个值,大于k个的剪掉即可
class Solution {
public:
    typedef vector<vector<int> > VectorArray;
    int m_n,m_k;
    VectorArray result;
    vector<int> solution;

    void dfs(int level){
        if( solution.size() == m_k){
            result.push_back(solution);
            return;
        }
        for(int i = level; i <= m_n; ++ i){
            solution.push_back(i);
            dfs(i+1);
            solution.pop_back();
        }
    }

    VectorArray combine(int n, int k){
        m_n = n, m_k = k;
        dfs(1);
        return result;
    }
};

 

posted @ 2014-06-21 18:24  OpenSoucre  阅读(131)  评论(0编辑  收藏  举报