[leetcode] Combinations

来源:互联网 发布:淘宝台式机哪家 编辑:程序博客网 时间:2024/05/01 20:59
CombinationsApr 18 '12

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

DFS算法,需要判断每次run运行时,当前v中需要添加的元素个数是否不大于n中剩余元素的个数,即判断k-v.size()<=n-(dep-1)是否成立,之后不将dep加入v,或者将dep加入v,两种情况,调用两遍run。
class Solution {    vector<vector<int> > ret;public:    vector<vector<int> > combine(int n, int k) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        ret.clear();        if(n<1 || k<1 || k>n) return ret;        vector<int> v;        run(v, 1, n, k);        return ret;            }        void run(vector<int> &v, int dep, int n, int k)    {        if(v.size()==k)         {            ret.push_back(v);            return;        }        if(k-v.size()>n-dep+1)            return;        run(v, dep+1, n, k);        v.push_back(dep);        run(v, dep+1, n, k);        v.pop_back();};


原创粉丝点击