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

  • 相关阅读:
    (ZOJ 3329) One Person Game (概率DP)
    python爬虫之json数据处理
    1034 Head of a Gang 图的遍历,map使用
    1030 Travel Plan Dijkstra+dfs
    vs C++ scanf 不安全
    1021. Deepest Root DFS 求最长无环路径
    1013. Battle Over Cities 用dfs计算联通分量
    无法解析的外部符号
    PAT DFS,BFS,Dijkstra 题号
    1004 Counting Leaves 对于树的存储方式的回顾
  • 原文地址:https://www.cnblogs.com/chruny/p/4926306.html
Copyright © 2011-2022 走看看