[Leetcode] (python): 039-combination Sum

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.