PathSumIIIOPT [source code]
public class PathSumIIIOPT {
static
public class Solution {
HashMap<Integer, Integer> preSum = new HashMap<>();
int sum;
public int pathSum(TreeNode root, int sum) {
if (root == null) return 0;
this.sum = sum;
preSum.put(0, 1);
return helper(root, 0);
}
int helper(TreeNode root, int currSum) {
if (root == null) return 0;
currSum += root.val;
int target = currSum - sum, ret = 0;
Integer cnt = preSum.get(target);
if (cnt != null && cnt > 0) {
ret += cnt;
}
preSum.put(currSum, preSum.getOrDefault(currSum, 0) + 1);
ret += helper(root.left, currSum) + helper(root.right, currSum);
preSum.put(currSum, preSum.get(currSum) - 1);
return ret;
}
}
public static void main(String[] args) {
PathSumIIIOPT.Solution tester = new PathSumIIIOPT.Solution();
}
}
这个是 submission 最优解: 18(91);
OPT2才是作者发布在discussion 上的版本, 看那个比较好;
看这种直接从 submission 上面拉下来的代码的时候, 很多时候都看的有点云里雾里, 因为不知道人家一个变量或者一个名字到底代表的是什么意思; 这种事情如果是以后工作了估计也可能还是会碰到, 所以看代码的时候, 还是要动用一点自己的技巧来帮助推理别人作者一个名字背后到底是什么意思:
比如这里, 首先 helper 是一个 recursion, 那么我们说过, 看到 helper, 你比较敏感的应该是参数表的变化, 已经返回值的含义. 这里返回值先不考虑, 参数表怎么变化的? 我们点到 helper 的名字, 看看 helper 的 usage, 就看到了 recursive call 的地方, 这里可以看到arg2好像没有变化? 实际上是有变化的, 这里的作者是直接把 currSum 作为一个 local var 来用了; 所以中途 currSum 是有变化的; 根据这个变化, 你就可以猜测 currSum 背后代表的含义, 比如它加了什么, 然后结合返回值的含义, 推测这个参数在整个过程中起的作用; 类似的, 你当然还要看 helper 的main call, arg2最开始是什么值(这里是0);
类似的, 怎么推测 preSum 的作用? 这个是一个dictionary, 我们找这个名字什么时候被更新, 尤其是什么时候被 get 和 put: 可以看到有一个cnt = preSum.get的操作, 大概可以猜测里面存放的应该是一个类似 count 的东西;
Problem Description
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:
- 5 -> 3
- 5 -> 2 -> 1
- -3 -> 11
Difficulty:Easy
Category:Algorithms
Acceptance:39.49%
Contributor: Stomach_ache
Related Topics
tree
Similar Questions
Path Sum Path Sum II