leetcode 39.组合总数

题目要求
给出一个不含重复元素的数组 candidates 和目标值 target ,返回由candidates 中的元素组成的数组,每个数组中元素的和等于 targetcandidates 中的元素可重复使用。

示例

输入: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 根据值确定变量的地址的方法还未知,留作近期任务。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值