给你一个 无重复元素 的整数数组 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
输出: []
搜索回溯
时间复杂度:O(S),**其中 S 为所有可行解的长度之和。从分析给出的搜索树我们可以看出时间复杂度取决于搜索树所有叶子节点的深度之和,即所有可行解的长度之和。**在这题中,我们很难给出一个比较紧的上界,我们知道 O(n×2n) 是一个比较松的上界,即在这份代码中,n 个位置每次考虑选或者不选,如果符合条件,就加入答案的时间代价。但是实际运行的时候,因为不可能所有的解都满足条件,递归的时候我们还会用
t
a
r
g
e
t
−
c
a
n
d
i
d
a
t
e
s
[
i
d
x
]
≥
0
target−candidates[idx]≥0
target−candidates[idx]≥0进行剪枝,所以实际运行情况是远远小于这个上界的。
空间复杂度:
O
(
t
a
r
g
e
t
)
O(target)
O(target)。除答案数组外,空间复杂度取决于递归的栈深度,在最差情况下需要递归
O
(
t
a
r
g
e
t
)
O(target)
O(target)层。
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
def dfs(begin, path, target):
if target < 0:
return
if target == 0:
res.append(path)
return
# target每减去一个数candidates[index],就向path中添加这个数candidates[index]
for index in range(begin, size):
dfs(index, path + [candidates[index]], target - candidates[index])
size = len(candidates)
res = []
dfs(0, [], target)
return res
给定一个候选人编号的集合 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用 一次 。
注意:解集不能包含重复的组合。
示例 1:
输入: candidates = [10,1,2,7,6,1,5], target = 8,
输出:
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]
示例 2:
输入: candidates = [2,5,2,1,2], target = 5,
输出:
[
[1,2,2],
[5]
]
搜索回溯
由第 39 题我们知道,数组 candidates 有序,也是 深度优先遍历 过程中实现「剪枝」的前提。
将数组先排序的思路来自于这个问题:去掉一个数组中重复的元素。很容易想到的方案是:先对数组 升序 排序,重复的元素一定不是排好序以后相同的连续数组区域的第 1 个元素。也就是说,剪枝发生在:同一层数值相同的结点第 2、3 … 个结点,因为数值相同的第 1 个结点已经搜索出了包含了这个数值的全部结果,同一层的其它结点,候选数的个数更少,搜索出的结果一定不会比第 1 个结点更多,并且是第 1 个结点的子集。
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
size = len(candidates)
res = []
def dfs(begin, path, target):
if target < 0:
return
if target == 0:
res.append(path)
return
# target每减去一个数candidates[index],就向path中添加这个数candidates[index]
for index in range(begin, size):
if index > begin and candidates[index - 1] == candidates[index]:
continue
dfs(index + 1, path + [candidates[index]], target - candidates[index])
candidates.sort()
dfs(0, [], target)
return res