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

  • 相关阅读:
    程序员的四个阶段
    2010Year Plans
    HttpHandler HttpModule入门篇
    Lucene.net索引文件的并发访问和线程安全性
    stream流写到MemoryStream内存流引发得问题
    ASP.NET 2.0 多文件上传小经验
    HTML 迷魂灯
    如何在Windows下搭建Android开发环境
    利用Lucene.net搭建站内搜索(4)数据检索
    数据加密和解密
  • 原文地址:https://www.cnblogs.com/chruny/p/4926306.html
Copyright © 2011-2022 走看看