HOT 100 › 索引 › B10 回溯 Backtracking
LC 39组合总和Combination Sum 中等
给定互异正整数数组 candidates 与目标 target,找出所有和为 target 的组合,同一个数可被无限次选取。
思路 回溯 dfs(start, remain):递归传 i 允许重复取,start 不回退避免重复组合;remain 为 0 收集答案。
class Solution: def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: ans, path = [], [] def dfs(start, remain): if remain == 0: ans.append(path[:]) return for i in range(start, len(candidates)): if candidates[i] > remain: continue path.append(candidates[i]) dfs(i, remain - candidates[i]) path.pop() dfs(0, target) return ans