LeetCode 39. Combination Sum
Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.
The same repeated number may be chosen from candidates unlimited number of times.
Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
Example 1:
Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
[7],
[2,2,3]
]
Example 2:
Input: candidates = [2,3,5], target = 8,
A solution set is:
[
[2,2,2,2],
[2,3,3],
[3,5]
]
解题思路
该程序需要求出给定数组中数字的组合,使得能够正好组成给定的和(target),并且数组中的数字能够重复使用。解决该问题能够用到递归的方法,即首先对数组由大到小排序,遍历数组中的每一个数,每一层遍历生成更接近于target的数的组合。在每一层递归中,若组合超过了target,则忽略该组合(不符合要求)。若组合正好为target,则添加该组合进入答案(ans)。若组合小于target,则继续递归到下一层。最终答案存储在列表ans中。
源代码
class Solution(object):
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
candidates.sort()
ans = []
self.dfs(candidates, target, 0, [], ans)
return ans
def dfs(self, arrays, target, pos, path, ans):
if target < 0:
return
if target == 0:
ans.append(path)
return
for i in range(pos, len(arrays)):
self.dfs(arrays, target - arrays[i], i, path + [arrays[i]], ans)