Leecode hot100 - 39. 组合总和
题目描述
39. 组合总和 - 力扣(LeetCode)
给你一个 无重复元素 的整数数组 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 输出: []
思路
强推K神的解法,真是神中神
先对候选数组排序,为后续剪枝做准备
定义递归函数backward
,参数包括当前组合state
、剩余目标值target
、候选数组choices
、起始索引start
和结果集res,
终止条件:当剩余目标值为 0 时,将当前组合加入结果
遍历从start
开始的候选元素(避免重复组合)
若当前元素大于剩余目标值,直接跳出循环(利用排序特性,后续元素更大)
选择当前元素加入组合,更新剩余目标
递归探索下一层
回溯:移除最后加入的元素,恢复状态
代码
class Solution:def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:def backward(state:list[int], target:int, choices:list[int], start:int, res:list[list[int]]):# 递归结束的标志,凑齐targetif target == 0:# 把当前结果加入res.append(list(state))return # 遍历所有的选择,从start开始遍历,避免生成重复子集for i in range(start, len(choices)):#若子集和超过 target, 则直接结束循环if target - choices[i] < 0:break# 尝试:做出选择,更新 target, startstate.append(choices[i])# 进行下一轮选择backward(state, target-choices[i], choices, i, res)# 回退:撤销选择,恢复到之前的状态state.pop()# 状态子集,即记录每个符合条件的结果state = []candidates.sort() # 排序,方便计算# 遍历的起始位置start = 0# 存储结果res = []backward(state, target, candidates, start, res)return res