# 给你一个无重复元素的整数数组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 # 输出: [] candidates = [2, 3, 6, 7] target = 7 path = [] res = [] def call_back(start_index, candidates, path): if sum(path)>target: return if sum(path) == target: res.append(path[:]) return for i in range(start_index, len(candidates)): path.append(candidates[i]) call_back(i, candidates, path) path.pop() return res result = call_back(0, candidates, path) print(result)
6.回溯算法-组合总和1.py
最新推荐文章于 2024-09-27 15:30:00 发布