Source of the topic:
https://leetcode.com/problems/combination-sum/
Test Instructions Analysis:
Enter a set and a target to find out so that the sum of the numbers inside the set equals the combination of target. The combinations must be sorted in dictionary order.
Topic Ideas:
Because the combinations must be sorted in dictionary order. Then the set is sorted first. It is not difficult to find that the topic can be divided into two cases, the first combination does not include set[0], this situation is removed set[0], and the other is to include set[0], this is the case target-set[0]. Solve the problem by handing it back.
Code (Python):
1 classsolution (object):2 defboolcombinationsum (self, candidates, target,j):3Ans = [];size =Len (candidates)4 iftarget = =0:5 return []6 ifSize < J + 1orTarget <0:7 return[[-1]]8TMP1 = self.boolcombinationsum (candidates,target,j + 1); tmp2 = Self.boolcombinationsum (Candidates,target-candidates[j],j)9 ifLen (tmp2) = =0:Ten ans.append ([candidates[j]]) One elifTMP2! = [[-1]]: A forIinchRange (len (TMP2)): -Ans.append ([candidates[j]] +Tmp2[i]) - ifLen (TMP1)! = 0 andTmp1! = [[-1]]: the forIinchRange (len (TMP1)): - ans.append (Tmp1[i]) - ifLen (TMP2)! = 0 andTMP1 = = [[-1]] andTMP2 = = [[-1]]: - return[[-1]] + returnans - defcombinationsum (self, candidates, target): + """ A : Type Candidates:list[int] at : Type Target:int - : Rtype:list[list[int]] - """ - Candidates.sort () -Ans =self.boolcombinationsum (candidates,target,0) - ifans = = [[-1]]: in return [] - returnAns
View Code
Reprint Please specify source: http://www.cnblogs.com/chruny/p/4926306.html
[Leetcode] (python): 039-combination Sum