39. Combination Sum leetcode python 2016 new season
2016-01-23 13:48
639 查看
Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where
the candidate numbers sums to T.
The same repeated number may be chosen from C unlimited number of times.
Note:
All numbers (including target) will be positive integers.
Elements in a combination (a1, a2,
… , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤
… ≤ ak).
The solution set must not contain duplicate combinations.
For example, given candidate set
A solution set is:
class Solution(object):
def bfs(self, candidates, target, start, valuelist, result):
if target == 0:
return result.append(valuelist)
for index in range(start, len(candidates)):
if target < candidates[index]:
return
self.bfs(candidates, target - candidates[index], index, valuelist + [candidates[index]], result)
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
candidates.sort()
result = []
self.bfs(candidates, target, 0, [], result)
return result
the candidate numbers sums to T.
The same repeated number may be chosen from C unlimited number of times.
Note:
All numbers (including target) will be positive integers.
Elements in a combination (a1, a2,
… , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤
… ≤ ak).
The solution set must not contain duplicate combinations.
For example, given candidate set
2,3,6,7and target
7,
A solution set is:
[7]
[2, 2, 3]
class Solution(object):
def bfs(self, candidates, target, start, valuelist, result):
if target == 0:
return result.append(valuelist)
for index in range(start, len(candidates)):
if target < candidates[index]:
return
self.bfs(candidates, target - candidates[index], index, valuelist + [candidates[index]], result)
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
candidates.sort()
result = []
self.bfs(candidates, target, 0, [], result)
return result
相关文章推荐
- [leetcode]87. Scramble String @python
- leetcode之Odd Even Linked List
- Python利用rsync自动同步服务器与本地文件同步
- jenkinsapi 0.2.29 : Python Package Index
- 在python中使用正则表达式查找可嵌套字符串组
- Python包管理工具
- Python
- Python集成开发环境(Eclipse+Pydev)
- Python闭包
- python——django使用mysql数据库(二)
- python学习笔记Day2
- python——django使用mysql数据库(一)
- python 学习第十二课
- python学习第十二课
- 深入Python(1): 字典排序 关于sort()、reversed()、sorted()
- 【Python】(有图)Win8.1 Python3.4.2安装
- <LeetCode><Easy> 328. Odd Even Linked List
- Python随手笔记第一篇(2)之初识列表和元组
- Python字符串、元组、列表、字典互相转换的方法
- [Python for Data Analysis] 环境及帮助查询