leetcode hot 100搜索回溯

39. 组合总和

已解答

中等

相关标签

相关企业

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

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

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

import copy

class Solution(object):

def combinationSum(self, candidates, target):

"""

:type candidates: List[int]

:type target: int

:rtype: List[List[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,candidates[index:])

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,candidates[index:])

相关推荐
2401_841495643 小时前
【计算机视觉】基于复杂环境下的车牌识别
人工智能·python·算法·计算机视觉·去噪·车牌识别·字符识别
Jonkin-Ma3 小时前
每日算法(1)之单链表
算法
晚风残3 小时前
【C++ Primer】第六章:函数
开发语言·c++·算法·c++ primer
杨云强3 小时前
离散积分,相同表达式数组和公式
算法
地平线开发者3 小时前
征程 6 | BPU trace 简介与实操
算法·自动驾驶
满天星83035773 小时前
【C++】AVL树的模拟实现
开发语言·c++·算法·stl
Lris-KK4 小时前
力扣Hot100--94.二叉树的中序遍历、144.二叉树的前序遍历、145.二叉树的后序遍历
python·算法·leetcode
麦麦鸡腿堡5 小时前
Java的动态绑定机制(重要)
java·开发语言·算法
zy_destiny5 小时前
【工业场景】用YOLOv8实现抽烟识别
人工智能·python·算法·yolo·机器学习·计算机视觉·目标跟踪
坚持编程的菜鸟5 小时前
LeetCode每日一题——螺旋矩阵
c语言·算法·leetcode·矩阵