leetcode hot 100搜索回溯

39. 组合总和

已解答

中等

相关标签

相关企业

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

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

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

import copy

class Solution(object):

def combinationSum(self, candidates, target):

"""

:type candidates: Listint

:type target: int

:rtype: ListList\[int]

"""

当成一棵树来遍历回溯条件是大于target

self.ret = \[\]

def dfs(target , current,current_list,candidates):

if current==target:

self.ret.append(copy.deepcopy(current_list))

elif current>target:

return

else:

for index,i in enumerate(candidates):

current+=i

current_list.append(i)

dfs(target,current,current_list,candidatesindex:)

del current_list-1

current-=i

current = 0

current_list = \[\]

dfs(target , current,current_list,candidates)

return self.ret

需要注意的是,candidates需要每次只能搜索到后面的dfs(target,current,current_list,candidatesindex:)

相关推荐
动词ing2 分钟前
【题目练习】全排列
算法
易小尊38 分钟前
Dixon-Coles 的 τ 函数,我写错了三次
算法
weixin_435208161 小时前
大模型面试宝典—大模型(LLMs)基础面
人工智能·职场和发展·agent
凯瑟琳.奥古斯特2 小时前
力扣1015C++解法技巧
c++·算法·leetcode·链表·职场和发展
seowmt2 小时前
GEO效果该什么时候看数据:从立项到复盘的时间线复盘
算法·ip·seo·geo·faq
悠仁さん2 小时前
【算法C++】双指针(一)
数据结构·c++·算法
文丑颜不良啊2 小时前
LeetCode626~650题目解析
java·leetcode
小豆庄2 小时前
本地视频脱敏的追踪系统踩坑——车牌过滤、转场误判与ID冲突排查
人工智能·算法·目标检测·音视频·视频·敏捷流程·纹理贴图
忆挽篱笙歌2 小时前
进程替换函数与shenll命令行解释器
前端·javascript·算法
YukiRinLL2 小时前
字符串存储与 BF、KMP 匹配算法
数据结构·算法