1. 程式人生 > >leetcode437. 路徑總和 III

leetcode437. 路徑總和 III

https://leetcode-cn.com/problems/path-sum-iii
暴力求解,耗時較長。注意程式碼中的pathSum函式表示從root向下,取任一點出發到任一點結束狀況下路徑和為sum的路徑個數;而get_path函式表示從node出發,到任一點結束狀況下路徑和為sum的路徑個數。所以,從根節點出發的pathSum等於從根節點出發的get_path加上分別從左右子樹出發的pathSum。

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def pathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: int
        """
        count = 0
        if not root:
            return count
        return self.get_path(root, sum) + \
               self.pathSum(root.left, sum) + self.pathSum(root.right, sum)

    def get_path(self, node, num):
        cnt = 0
        if node.val == num:
            cnt += 1
        if node.left:
            cnt += self.get_path(node.left, num-node.val)
        if node.right:
            cnt += self.get_path(node.right, num-node.val)
        return cnt


上面的解答耗時太久,可以把重複子問題的求解優化下。
在這裡插入圖片描述

class Solution:
    def pathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: int
        """
        self.res = 0
        if not root:
            return 0
        log = {0:1}  # 記錄之前路徑和
        self.dfs(root, 0, log, sum)
        return self.res

    def dfs(self, root, root_sum, log, sum):
        if root:
            root_sum += root.val
            self.res += log.get(root_sum-sum, 0)
            log[root_sum] = log.get(root_sum, 0) + 1
            self.dfs(root.left, root_sum, log, sum)
            self.dfs(root.right, root_sum, log, sum)
            log[root_sum] -= 1