[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]
View Code
转载请注明出处:http://www.cnblogs.com/chruny/p/4926306.html
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
相关文章推荐
- python基础-线程和进程
- [LeetCode]题解(python):038-Count and Say
- [LeetCode]题解(python):037-Sudoku Solver
- Python Excel解析
- 支持Python3的图表库
- Ubuntu 14.04 安装 Python3
- Python验证码识别处理实例
- [LeetCode]题解(python):036-Valid Sudoku
- 4.2 codecs--Codec注册管理和基类(2)
- Python JSON 解析
- LeetCode----Invert Binary Tree
- python笔记004—字符串应用
- Python的C扩展问题
- 半自动抓取知乎用户的微博地址(python)(2)
- Python信号标准库(signal包,部分os包)
- python switch +=*/计算器 和 导入自定义模块 简单操作
- python的一些问题以及处理思路
- Python 创建XML
- Python XML的解析与创建
- python 文本解析 XML基础