问题描述
- “组合总和”问题就是给定一个数组和一个目标数字,求出数组中的和为这个目标数字的子数组的集合。
- 这类问题本质就是使用“回溯”的方法解决,但因为设定条件的不同,解法上有一定差异。
- leetcode上目前有4个“组合总和”问题,下面一一介绍它们的解法
leetcode 39. 组合总和
- 给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
- 其中,candidates中的数字可以被重复选取
- 也就是说当candidates=[1, 2], target=3 时,[1,1,1]也是一个符合条件的答案,最终应输出[[1,2], [1,1,1]]
- 代码:
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
def traceback(res, path, curr_sum, pos):
if curr_sum == target:
res.append(path[:])
return
for i in range(pos, len(candidates)):
if curr_sum + candidates[i] > target:
break
path.append(candidates[i])
traceback(res, path, curr_sum+candidates[i], i)
path