039 combination Sum
The problem is brute force search, but there is an optimization is line 14 plus an if a[s] > target does not need to repeat the search so that the runtime will change from 236ms to 108ms
1 classSolution:2 #@param {integer[]} candidates3 #@param {integer} target4 #@return {integer[][]}5 defcombinationsum (self, candidates, target):6 Candidates.sort ()7Ans = []8 self.help (candidates, Target, [], 0, ans)9 returnansTen One defHelp (self, a, target, cur, s, ans): A iftarget = =0: - ans.append (cur[:]) - ifTarget < 0orA[s] >Target: the return - whiles <Len (a): - cur.append (A[s]) -R = Self.help (A, target-A[s], cur, s, ans) + Cur.pop () -s + = 1
Then further optimize the following line 20 plus a break, because if the current a[s] has exceeded target, there is no need to continue the search, so that the run time into 88ms
1 classSolution:2 #@param {integer[]} candidates3 #@param {integer} target4 #@return {integer[][]}5 defcombinationsum (self, candidates, target):6 Candidates.sort ()7Ans = []8 self.help (candidates, Target, [], 0, ans)9 returnansTen One defHelp (self, a, target, cur, s, ans): A iftarget = =0: - ans.append (cur[:]) - ifTarget < 0orA[s] >Target: the return - whiles <Len (a): - cur.append (A[s]) -R = Self.help (A, target-A[s], cur, s, ans) + Cur.pop () - ifTarget-a[s] <0: + Break As + = 1
039 combination Sum