feature/437: add a faster solution

This commit is contained in:
novahe
2021-05-02 17:33:57 +08:00
parent 9c0603ea84
commit 4abb13e6ca
2 changed files with 23 additions and 1 deletions

View File

@ -39,3 +39,25 @@ func findPath437(root *TreeNode, sum int) int {
res += findPath437(root.Right, sum-root.Val)
return res
}
func pathSum(root *TreeNode, targetSum int) int {
prefixSum := make(map[int]int)
prefixSum[0] = 1
return dfs(root, prefixSum, 0, targetSum)
}
func dfs(root *TreeNode, prefixSum map[int]int, cur, sum int) int {
if root == nil {
return 0
}
cur += root.Val
cnt := 0
if v, ok := prefixSum[cur-sum]; ok {
cnt = v
}
prefixSum[cur]++
cnt += dfs(root.Left, prefixSum, cur, sum)
cnt += dfs(root.Right, prefixSum, cur, sum)
prefixSum[cur]--
return cnt
}

View File

@ -45,7 +45,7 @@ func Test_Problem437(t *testing.T) {
_, p := q.ans437, q.para437
fmt.Printf("【input】:%v ", p)
root := structures.Ints2TreeNode(p.one)
fmt.Printf("【output】:%v \n", pathSumIII(root, p.sum))
fmt.Printf("【output】:%v \n", pathSum(root, p.sum))
}
fmt.Printf("\n\n\n")
}