Skip to content

Commit 65f4c4f

Browse files
authored
Merge pull request #122 from NovaHe/feature/437
feature/437: add a faster solution
2 parents 1071ae0 + 4abb13e commit 65f4c4f

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

leetcode/0437.Path-Sum-III/437. Path Sum III.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,3 +39,25 @@ func findPath437(root *TreeNode, sum int) int {
3939
res += findPath437(root.Right, sum-root.Val)
4040
return res
4141
}
42+
43+
func pathSum(root *TreeNode, targetSum int) int {
44+
prefixSum := make(map[int]int)
45+
prefixSum[0] = 1
46+
return dfs(root, prefixSum, 0, targetSum)
47+
}
48+
49+
func dfs(root *TreeNode, prefixSum map[int]int, cur, sum int) int {
50+
if root == nil {
51+
return 0
52+
}
53+
cur += root.Val
54+
cnt := 0
55+
if v, ok := prefixSum[cur-sum]; ok {
56+
cnt = v
57+
}
58+
prefixSum[cur]++
59+
cnt += dfs(root.Left, prefixSum, cur, sum)
60+
cnt += dfs(root.Right, prefixSum, cur, sum)
61+
prefixSum[cur]--
62+
return cnt
63+
}

leetcode/0437.Path-Sum-III/437. Path Sum III_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ func Test_Problem437(t *testing.T) {
4545
_, p := q.ans437, q.para437
4646
fmt.Printf("【input】:%v ", p)
4747
root := structures.Ints2TreeNode(p.one)
48-
fmt.Printf("【output】:%v \n", pathSumIII(root, p.sum))
48+
fmt.Printf("【output】:%v \n", pathSum(root, p.sum))
4949
}
5050
fmt.Printf("\n\n\n")
5151
}

0 commit comments

Comments
 (0)