[LeetCode] Path Sum I/II/III 回溯算法全解

本文深入解析了LeetCode上路径总和系列问题(Path Sum I/II/III)的回溯算法解决方案,包括如何通过决策树遍历找到所有可能的路径,使路径上的数值和等于给定的数值。文章详细介绍了回溯算法的基本框架,以及在具体问题中如何确定路径、选择列表和结束条件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[LeetCode] Path Sum I/II/III 回溯算法全解

回溯算法的框架:

参考文章.
解决一个回溯问题,实际上就是一个决策树的遍历过程。你只需要思考 3 个问题:
1、路径:也就是已经做出的选择。
2、选择列表:也就是你当前可以做的选择。
3、结束条件:也就是到达决策树底层,无法再做选择的条件。

result = []
def backtrack(路径, 选择列表):
    if 满足结束条件:
        result.add(路径)
        return

    for 选择 in 选择列表:
        做选择
        backtrack(路径, 选择列表)
        撤销选择

112. Path Sum

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

Note:

A leaf is a node with no children.

Example:

Given the below binary tree and sum = 22,

      5
     / \
    4   8
   /   / \
  11  13  4
 /  \      \
7    2      1

return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

Python3 Solution:

class Solution:
    def hasPathSum(self, root: TreeNode, sum: int) -> bool:
        if not root:
            return False
        
        def backtrack(root, track, sum):
            if not root.left and not root.right:
                if root.val + track == sum:
                    return True 
                return False 
            # 选择列表只有左右节点
            if root.left:
                if backtrack(root.left, track+root.val, sum):
                    return True
            if root.right:
                if backtrack(root.right, track+root.val, sum):
                    return True
            return False
            
        track = 0
        return backtrack(root, track, sum)

113. Path Sum II

Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.

Note:

A leaf is a node with no children.

Example:

Given the below binary tree and sum = 22,

      5
     / \
    4   8
   /   / \
  11  13  4
 /  \    / \
7    2  5   1

Return:

[
   [5,4,11,2],
   [5,8,4,5]
]

Python3 Solution:

class Solution:
    def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]:
        if not root:
            return []
        
        def backtrack(root, track, trackSum, sum):
            if not root.left and not root.right:
                if root.val + trackSum == sum:
                    track.append(root.val)
                    res.append(track[:])
                    track.pop()
                return
            track.append(root.val) 
            if root.left:
                backtrack(root.left, track, trackSum+root.val, sum)
            if root.right:
                backtrack(root.right, track, trackSum+root.val, sum)
            track.pop()
            
        res, track, trackSum = [], [], 0
        backtrack(root, track, trackSum, sum)
        return res

437. Path Sum III

You are given a binary tree in which each node contains an integer value.

Find the number of paths that sum to a given value.

The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).

The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.

Example:

root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8

      10
     /  \
    5   -3
   / \    \
  3   2   11
 / \   \
3  -2   1

Return 3. The paths that sum to 8 are:

1.  5 -> 3
2.  5 -> 2 -> 1
3. -3 -> 11

Python3 Solution:

class Solution:
    def pathSum(self, root: TreeNode, sum: int) -> int:
        if not root:
            return 0
        trackSum = defaultdict(lambda: 0) 
        trackSum[0] = 1   
        self.res, track = 0, 0
        
        def backtrack(root, track, sum):
            if not root.left and not root.right:
                track = track + root.val
                if track - sum in trackSum:
                    self.res = self.res + trackSum[track - sum]
                track = track - root.val
                return
            track = track + root.val
            if track - sum in trackSum:
                self.res = self.res + trackSum[track - sum]            
            trackSum[track] += 1    
            if root.left:
                backtrack(root.left, track, sum)
            if root.right:
                backtrack(root.right, track, sum)
            trackSum[track] -= 1
            track = track - root.val
                                    
        backtrack(root, track, sum)
        return self.res
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值