# Leetcode 39：组合总和（最详细的解法！！！）

candidates 中的数字可以无限制重复被选取。

• 所有数字（包括 target）都是正整数。
• 解集不能包含重复的组合。

输入: candidates = [2,3,6,7], target = 7,

[
[7],
[2,2,3]
]


输入: candidates = [2,3,5], target = 8,

[
[2,2,2,2],
[2,3,3],
[3,5]
]


2 2 2 2


2 2 2


2 2


class Solution:
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
result = list()
candidates.sort()
self._combinationSum(candidates, target, 0, list(), result)
return result

def _combinationSum(self, nums, target, index, path, res):
if target < 0:
return

if target == 0:
res.append(path)
return

for i in range(index, len(nums)):
self._combinationSum(nums, target-nums[i], i, path+[nums[i]], res)


class Solution:
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
result = list()
candidates.sort()
self._combinationSum(candidates, target, 0, list(), result)
return result

def _combinationSum(self, nums, target, index, path, res):
if target == 0:
res.append(path)
return

if path and target < path[-1]:
return

for i in range(index, len(nums)):
self._combinationSum(nums, target-nums[i], i, path+[nums[i]], res)


class Solution:
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
result = list()
candidates.sort()
self._combinationSum(candidates, target, 0, list(), result)
return result

def _combinationSum(self, nums, target, index, path, res):
if target == 0:
res.append(path)
return

if index == len(nums) or (path and target < path[-1]):
return

self._combinationSum(nums, target, index + 1, path, res) # 不放入
self._combinationSum(nums, target - nums[index], index, path + [nums[index]], res) #放入


class Solution(object):
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
candidates = sorted(set(candidates))
result = list()
stack = [(0, list(), target)]
cand_len = len(candidates)

while stack:
i, path, remain = stack.pop()
while i < cand_len:
if path and remain < path[-1]:
break
if candidates[i] == remain:
result.append(path + [candidates[i]])
stack += [(i, path + [candidates[i]],  remain - candidates[i])]
i+=1

return result


©️2019 CSDN 皮肤主题: 技术黑板 设计师: CSDN官方博客