回溯
一杯小熊
这个作者很懒,什么都没留下…
展开
-
LeetCode 78 子集
class Solution: def subsets(self, nums: List[int]) -> List[List[int]]: ''' #回溯1 res = [] n = len(nums) def back_track(index, path): res.append(path) for i in range(index, n): ...原创 2021-04-12 21:55:04 · 51 阅读 · 0 评论 -
关于回溯中是否需要拷贝path的复制以及是否需要进行path.pop()操作的两种思路
来自对LeetCode39题,组合总和的一点思考在写回溯的时候,往往需要添加path的一个拷贝,即res.append(path[:]),然后最后回溯的时候再path.pop(),但是如果path + [num],就不用拷贝复制以及pop操作了。class Solution: def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: #这里有.原创 2021-03-29 11:37:49 · 608 阅读 · 0 评论 -
LeetCode 39 组合总和
经典回溯题目 + 剪枝 + 避免重复class Solution: def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: path = [] #当前路径 res = [] #保存结果列表 #回溯函数 def back_track(candidates, target, index): ..原创 2021-03-29 10:44:55 · 52 阅读 · 0 评论 -
剑指Offer 34 二叉树中和为某一值的路径
思路:dfs + 回溯注意:如果语句写在递归下面就是回溯,当二叉树遍历完左子树回去的时候就会删除节点# Definition for a binary tree node.# class TreeNode:# def __init__(self, x):# self.val = x# self.left = None# self.right = Noneclass Solution: def pathSum(se..原创 2021-03-04 20:28:16 · 84 阅读 · 1 评论 -
LeetCode.No.22 括号生成
方法:回溯class Solution: def generateParenthesis(self, n: int) -> List[str]: res = [] def dfs(path, left, right, n): if left == n and right == n: res.append(path) if left < right: ...原创 2021-01-21 20:05:21 · 54 阅读 · 0 评论