zoukankan      html  css  js  c++  java
  • [LeetCode]题解(python):039-Combination Sum

    题目来源:

      https://leetcode.com/problems/combination-sum/


    题意分析:

      输入一个set和一个target,找出所以由set里面的数组成的相加等于target的组合。组合必须按照字典序排序。


    题目思路:

      由于组合必须按照字典序排序。那么首先将set排序。不难发现,题目可以分成两种情况,第一个组合不包括set[0],这种情况就去掉set[0];另外一种是包括set[0],这种情况就是将target - set[0]。用递归来解决这个问题即可。


    代码(python):

      

     1 class Solution(object):
     2     def boolcombinationSum(self, candidates, target,j):
     3         ans = [];size = len(candidates)
     4         if target == 0:
     5             return []
     6         if size < j + 1 or target < 0:
     7             return [[-1]]
     8         tmp1 = self.boolcombinationSum(candidates,target,j + 1);tmp2 = self.boolcombinationSum(candidates,target - candidates[j],j)
     9         if len(tmp2) == 0:
    10             ans.append([candidates[j]])
    11         elif tmp2 != [[-1]]:
    12             for i in range(len(tmp2)):
    13                 ans.append([candidates[j]] + tmp2[i])
    14         if len(tmp1) != 0 and tmp1 != [[-1]]:
    15             for i in range(len(tmp1)):
    16                 ans.append(tmp1[i])
    17         if len(tmp2) != 0 and tmp1 == [[-1]] and tmp2 == [[-1]]:
    18             return [[-1]]
    19         return ans
    20     def combinationSum(self, candidates, target):
    21         """
    22         :type candidates: List[int]
    23         :type target: int
    24         :rtype: List[List[int]]
    25         """
    26         candidates.sort()
    27         ans = self.boolcombinationSum(candidates,target,0)
    28         if ans == [[-1]]:
    29             return []
    30         return ans
    View Code

    转载请注明出处:http://www.cnblogs.com/chruny/p/4926306.html

  • 相关阅读:
    Git教程
    test
    Android中的权限机制
    Android中<uses-library>的理解
    权限机制
    总是听到有人说AndroidX,到底什么是AndroidX?Android和AndroidX的区别
    VMware Tools按钮变灰色,无法安装的解决方法
    VMware Tools (ubuntu系统)安装详细过程与使用
    Android studio常用快捷键
    CVE漏洞分析
  • 原文地址:https://www.cnblogs.com/chruny/p/4926306.html
Copyright © 2011-2022 走看看