Combinations

C(n,k) 回溯

    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>> res;
        vector<int> path;
        construct(1,n,k,path,res);
        return res;
        
    }
    
    bool construct(int pos,int n,int k,vector<int>& path,vector<vector<int>>& res)
    {
        if(k==0)
        {
            res.push_back(path);
            return true;
        }
        if(n-pos+1<k)
            return false;
        for(int i=pos;i<=n;i++)
        {
            path.push_back(i);
            construct(i+1,n,k-1,path,res);
            path.pop_back();
        }
        return true;
        
    }

  

posted @ 2013-10-05 15:09  summer_zhou  阅读(198)  评论(0编辑  收藏  举报