题目要求
给出一个不含重复元素的数组 candidates
和目标值 target
,返回由candidates
中的元素组成的数组,每个数组中元素的和等于 target
,candidates
中的元素可重复使用。
示例
输入:candidates = [2, 3, 6, 7], target = 7
输出:[[2, 2, 3], [7]]
dfs即可解决
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
def dfs(current_target, i, combination):
if current_target == 0:
res.append(combination)
return
if candidates[i] <= current_target:
# combination.append(candidates[i])
dfs(current_target - candidates[i], i, combination + [candidates[i]])
# combination.pop()
if i > 0:
dfs(current_target, i - 1, combination)
else:
return
candidates = sorted(candidates)
res = []
dfs(target, len(candidates) - 1, [])
return res
combination[]
不管是定义在combinationSum()
里还是 dfs()
里,当将一个符合要求的combination[]
加入到 res[]
后,如果combination[]
的值再发生改变,res[]
也会跟着改变,比如
a = [1, 2, 3]
b = []
b.append(a)
a.pop()
print(a, b)
执行结果为
[1, 2] [[1, 2]]
由此猜想b[0]
是对a
的引用,查看其地址也论证了这一点
print(id(a), id(b), id(b[0]))
4311129136 4311128656 4311129136
在dfs
过程中combination[]
及其地址变化如下
combination = [] , address of combination: 4504359552
combination = [5] , address of combination: 4505087024
combination = [5] , address of combination: 4505087024
combination = [5, 3] , address of combination: 4504033072
combination = [5] , address of combination: 4505087024
combination = [5, 2] , address of combination: 4505214320
combination = [] , address of combination: 4504359552
combination = [3] , address of combination: 4505214320
combination = [3, 3] , address of combination: 4505087504
combination = [3, 3] , address of combination: 4505087504
由此可见,只有在 combination[]
值发生变化的时候才会赋予其新的地址,即当dfs()
的参数 combination + [candidates[i]]
传到下一层时相当于对 combination
重新赋值
但是这里 python 根据值确定变量的地址的方法还未知,留作近期任务。