39. 组合总和(中)
题目
- 给你一个 无重复元素 的整数数组 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
输出: []
法一、回溯
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
def backtrack(candidates: List[int],target: int, track: List[int], res: List[List[int]]):
#如果减剩的最后结果为0,则将路径加入结果集
if target==0:
res.append(track[:])
return
if target < 0:
return
for i in range(len(candidates)):
track.append(candidates[i])#做选择
backtrack(candidates[i:], target - candidates[i],track,res)#递归调用,更新目标值为减去当前候选数后的值,并传递更新后的路径和结果集
#[i:]避免了重复的组合结果
track.pop()#撤销选择
res=[]#结果列表
track=[]#选择列表
backtrack(candidates,target,track,res)
return res
法二、动态规划
- 和经典的零钱问题类似(力扣518题)
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
# 创建一个二维的动态规划数组,dp[i] 表示凑出金额 i 的所有组合
dp = [[] for _ in range(target + 1)]
dp[0] = [[]] # base case,凑出目标金额为0的组合只有一个空组合
for i in range(1, target + 1):
for candidate in candidates:
if candidate <= i:
for comb in dp[i - candidate]:
if not comb or candidate >= comb[-1]:#判断最后一个元素是否小于等于候选数 candidate,以避免生成重复的组合。
dp[i].append(comb + [candidate])
return dp[target]