一、题目描述
给你一个 无重复元素 的整数数组 candidates
和一个目标整数 target
,找出 candidates
中可以使数字和为目标数 target
的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。
candidates
中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。
对于给定的输入,保证和为 target
的不同组合数少于 150
个。
示例 1
输入:candidates = [2,3,6,7], target = 7
输出:[[2,2,3],[7]]
解释:
2 和 3 可以形成一组候选,2 + 2 + 3 = 7 。注意 2 可以使用多次。
7 也是一个候选, 7 = 7 。
仅有这两种组合。
示例 2
输入: candidates = [2,3,5], target = 8
输出: [[2,2,2,2],[2,3,3],[3,5]]
示例 3
输入: candidates = [2], target = 1
输出: []
提示:
1 <= candidates.length <= 30
2 <= candidates[i] <= 40
candidates 的所有元素 互不相同
二、代码
代码如下:
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
#result是存储最后结果的二维数组
result = []
#path记录的是可能添加进入result的一维数组
path = []
def backtrack(candidates, target, sum, startIndex):
#如果 sum > target 则结束当前回溯
if sum > target:
return
#如果 sum == target 则记录下当前的path数组信息,然后结束当前回溯
if sum == target:
#path[:]表示重新给予一个新内存空间,后面用到path的地方不会被影响
return result.append(path[:])
#从startIndex开始遍历candidates数组
for i in range(startIndex, len(candidates)):
# 如果 sum + candidates[i] > target 就终止遍历
if sum + candidates[i] > target:
return
#否则就sum = sum + candidates
sum += candidates[i]
#在path一维数组中添加入当前值
path.append(candidates[i])
# startIndex = i:表示可以重复读取当前的数
backtrack(candidates, target, sum, i)
# 回溯 删除sum添加进入的值
sum -= candidates[i]
# 回溯 删除path刚刚添加进入的值(末尾的值)
path.pop()
candidates.sort()
backtrack(candidates, target, 0, 0)
print(result)
return result
三、解题思路
本题思路采用回溯法,大致解法就是不停的递归,用sum记录当前path数组中存储的数值之和,遍历candidates数组,将当前candidates中数值依次添加进sum,如果当前的sum<target,就继续向path数组中添加新的数值然后递归;如果当前的sum>target,则立刻结束当前的递归;如果sum=target,则将当前的path数组添加进入最后的结果result数组中并结束当前递归。