LeetCode 39. Combination Sum 时间复杂度(O( n^k​​​​​​​))

时间复杂度(O( n^k)),思想,DFS 深度遍历

class Solution {
public:
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        vector<vector <int > >vecvec;
        if(candidates.size()==0)return vecvec;
        vector<int> vec;
        combination(candidates,0,0,target,vec,-1,vecvec);
        return vecvec;
    }
    void combination(vector<int>& candidates,int index,int sum,int target,vector<int> recVec,int currvalue,vector<vector<int > > &vecvec){
        if(currvalue>0)     recVec.push_back(currvalue);
        if(sum==target)     vecvec.push_back(recVec);
        else if(sum<target&&index<candidates.size())
            for(int k=index;k<candidates.size();++k)
                if(sum+candidates[k]<=target)    
                    combination(candidates,k,sum+candidates[k],target,recVec,candidates[k],vecvec);
    }
};

 

阅读更多
换一批

没有更多推荐了,返回首页