题目来源:

  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

相关文章:

  • 2022-12-23
  • 2021-06-05
  • 2022-01-09
  • 2021-11-30
  • 2021-10-01
  • 2021-09-16
  • 2021-10-31
猜你喜欢
  • 2021-08-04
  • 2021-10-20
  • 2021-10-22
  • 2021-08-24
  • 2021-07-06
  • 2021-09-23
  • 2021-12-15
相关资源
相似解决方案