您的位置:首页 > 编程语言 > Python开发

[LeetCode]题解(python):039-Combination Sum

2015-10-31 21:45 555 查看
[b]题目来源:[/b]

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

[b]题意分析:[/b]

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

[b]题目思路:[/b]

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

[b]代码(python):[/b]

  

class Solution(object):
def boolcombinationSum(self, candidates, target,j):
ans = [];size = len(candidates)
if target == 0:
return []
if size < j + 1 or target < 0:
return [[-1]]
tmp1 = self.boolcombinationSum(candidates,target,j + 1);tmp2 = self.boolcombinationSum(candidates,target - candidates[j],j)
if len(tmp2) == 0:
ans.append([candidates[j]])
elif tmp2 != [[-1]]:
for i in range(len(tmp2)):
ans.append([candidates[j]] + tmp2[i])
if len(tmp1) != 0 and tmp1 != [[-1]]:
for i in range(len(tmp1)):
ans.append(tmp1[i])
if len(tmp2) != 0 and tmp1 == [[-1]] and tmp2 == [[-1]]:
return [[-1]]
return ans
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
candidates.sort()
ans = self.boolcombinationSum(candidates,target,0)
if ans == [[-1]]:
return []
return ans


View Code

转载请注明出处:http://www.cnblogs.com/chruny/p/4926306.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: