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:)

相关推荐
想吃火锅10053 分钟前
【leetcode】189.轮转数组js
开发语言·javascript·leetcode
大侠归来10 分钟前
cJSON 源码解析:parse_string 函数深入剖析
linux·网络·算法
余额瞒着我当琳1 小时前
C++ map 底层与AVL 树
开发语言·c++·算法
释厄6231 小时前
物理发展史·量子力学=节点2·牛顿力学=节点3·宇宙的语言算法AI
人工智能·算法·microsoft
CQU_JIAKE1 小时前
9.30【A】
算法
INGNIGHT2 小时前
1897 · 会议室 3(扫描线)
数据结构·算法
All for pursuit.2 小时前
【贪心-2】253.会议室 II
数据结构·c++·算法·leetcode
垆边人似月.2 小时前
华为机考题(一):质数因子
算法·华为
迷途之人不知返2 小时前
算法系列5:位运算
算法
牢姐与蒯2 小时前
c++加餐之位图
c++·算法·哈希