LeetCode 39. Combination Sum 時間複雜度(O( n^k))
阿新 • • 發佈:2019-01-23
時間複雜度(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); } };