diff --git "a/problems/0112.350円267円257円345円276円204円346円200円273円345円222円214円.md" "b/problems/0112.350円267円257円345円276円204円346円200円273円345円222円214円.md" index 2beb8a7fa3..6709a2fbd2 100644 --- "a/problems/0112.350円267円257円345円276円204円346円200円273円345円222円214円.md" +++ "b/problems/0112.350円267円257円345円276円204円346円200円273円345円222円214円.md" @@ -727,6 +727,48 @@ class Solution: ```go //递归法 +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func hasPathSum(root *TreeNode, targetSum int) bool { + if root == nil { + return false + } + return traversal(root, targetSum - root.Val) +} + +func traversal(cur *TreeNode, count int) bool { + if cur.Left == nil && cur.Right == nil && count == 0 { + return true + } + if cur.Left == nil && cur.Right == nil { + return false + } + if cur.Left != nil { + count -= cur.Left.Val + if traversal(cur.Left, count) { + return true + } + count += cur.Left.Val + } + if cur.Right != nil { + count -= cur.Right.Val + if traversal(cur.Right, count) { + return true + } + count += cur.Right.Val + } + return false +} +``` + +```go +//递归法精简 /** * Definition for a binary tree node. * type TreeNode struct { diff --git "a/problems/350円203円214円345円214円205円347円220円206円350円256円272円345円237円272円347円241円20001円350円203円214円345円214円205円-1.md" "b/problems/350円203円214円345円214円205円347円220円206円350円256円272円345円237円272円347円241円20001円350円203円214円345円214円205円-1.md" index 0c78e3f695..2e1cd52c23 100644 --- "a/problems/350円203円214円345円214円205円347円220円206円350円256円272円345円237円272円347円241円20001円350円203円214円345円214円205円-1.md" +++ "b/problems/350円203円214円345円214円205円347円220円206円350円256円272円345円237円272円347円241円20001円350円203円214円345円214円205円-1.md" @@ -193,7 +193,7 @@ dp[0][j],即:i为0,存放编号0的物品的时候,各个容量的背包 代码初始化如下: -``` +```CPP for (int j = 0 ; j < weight[0]; j++) { // 当然这一步,如果把dp数组预先初始化为0了,这一步就可以省略,但很多同学应该没有想清楚这一点。 dp[0][j] = 0; }

AltStyle によって変換されたページ (->オリジナル) /