LeetCodeCampsDay22回溯part02

39. 组合总和

https://leetcode.cn/problems/combination-sum/

给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。

candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。

对于给定的输入,保证和为 target 的不同组合数少于 150 个。

示例 1:

1
2
3
4
5
6
输入:candidates = [2,3,6,7], target = 7
输出:[[2,2,3],[7]]
解释:
2 和 3 可以形成一组候选,2 + 2 + 3 = 7 。注意 2 可以使用多次。
7 也是一个候选, 7 = 7 。
仅有这两种组合。

示例 2:

1
2
输入: candidates = [2,3,5], target = 8
输出: [[2,2,2,2],[2,3,3],[3,5]]

示例 3:

1
2
输入: candidates = [2], target = 1
输出: []

提示:

  • 1 <= candidates.length <= 30
  • 2 <= candidates[i] <= 40
  • candidates 的所有元素 互不相同
  • 1 <= target <= 40

回溯思路

  1. 77组合 ,以及 216.组合总和III 很像,唯一区别是start位置,在77组合里,每层for循环里的下一个递归函数start为i+1,而这题目里下一个递归函数start为i即可;同样使用一个path记录路径,必要时计算path的和
  2. 输入一个候选列表,目标值,以及开始位置of候选列表
  3. 终止条件:sum of path如果大于target则终止;如果等于target则res添加path
  4. 单层逻辑:把当前值添加到path,递归下一轮(注意start需要包含当前值),再让path将当前值弹出

如果,start值一直是0,会得到如[2,2,3],[3,2,2]这种重复的结果(注意题目要求不包含重复的组合)

img

回溯代码

  • 时间复杂度O(N * 2 ^ T)
  • 空间复杂度O(T)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution:
def __init__(self):
self.res = list()
self.path = list()


def foo(self, candidates: List[int], target: int, start: int = 0):
sumOfPath = sum(self.path)
if sumOfPath > target:
return
elif sumOfPath == target:
self.res.append(self.path[:])
return

L = len(candidates)
for i in range(start, L):
self.path.append(candidates[i])
self.foo(candidates, target, i)
self.path.pop()

def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
self.foo(candidates, target, 0)
return self.res

40. 组合总和 II

https://leetcode.cn/problems/combination-sum-ii/

给定一个候选人编号的集合 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的每个数字在每个组合中只能使用 一次

**注意:**解集不能包含重复的组合。

示例 1:

1
2
3
4
5
6
7
8
输入: candidates = [10,1,2,7,6,1,5], target = 8,
输出:
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]

示例 2:

1
2
3
4
5
6
输入: candidates = [2,5,2,1,2], target = 5,
输出:
[
[1,2,2],
[5]
]

提示:

  • 1 <= candidates.length <= 100
  • 1 <= candidates[i] <= 50
  • 1 <= target <= 30

回溯思路

本题目前一题目有点儿像,但不同点在于:本题要求不能有相同组合,第一想法是使用字典或set排队重复元素,但这样会导致超时(比如[1,1,1,1,…,1], target=30会发生超时);所以需要在每层处理时就进行去重复

  1. 输入还是candidates和target,以及start节点;
  2. 终止条件:sumOfPath > target则退出,等于target则添加到res;
  3. 单层逻辑:[剪枝]若sumOfPath + candidates[i]大于target则遍历下一个元素(或者直接return, 如果candiates已经排序过了),判断candidates[i - 1] == candidates[i],目的是防止相同的元素再参与

下面这图的重点是:同一层如果有重复元素就不重复选取了,而不同层如果有重复元素是可以重复选的;比如[1,1,1,1,1,…,1],target=30,对第一个1来说,后面的[1,1,1,1…,1]都可以选;而对第二个1来说

img

我在图中将used的变化用橘黄色标注上,可以看出在candidates[i] == candidates[i - 1]相同的情况下:

  • used[i - 1] == true,说明同一树枝candidates[i - 1]使用过
  • used[i - 1] == false,说明同一树层candidates[i - 1]使用过

可能有的录友想,为什么 used[i - 1] == false 就是同一树层呢,因为同一树层,used[i - 1] == false 才能表示,当前取的 candidates[i] 是从 candidates[i - 1] 回溯而来的。

而 used[i - 1] == true,说明是进入下一层递归,去下一个数,所以是树枝上,如图所示:

img

回溯代码

  • 时间复杂度: O(n * 2^n)
  • 空间复杂度: O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution:
def __init__(self):
self.res = list()
self.path = list()
self.sumOfPath = 0

def foo(self, candidates, target, start: int = 0):
if self.sumOfPath > target:
return
elif self.sumOfPath == target:
self.res.append(self.path[:])
return

L = len(candidates)

for i in range(start, L):
if self.sumOfPath + candidates[i] > target:
continue
# 要对同一树层使用过的元素进行跳过
if candidates[i - 1] == candidates[i] and i > start:
continue

self.sumOfPath += candidates[i]
self.path.append(candidates[i])
# 不带当前元素自身
self.foo(candidates, target, i + 1)

self.sumOfPath -= candidates[i]
self.path.pop()

def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
candidates = sorted(candidates)
self.foo(candidates, target)
return self.res