代码改变世界

Prefix Sum & Dictionary Time and Space O(n) for -- Find a number of continuous subarrays/submatrices/tree paths that sum to target

2021-06-18 20:31  Johnson_强生仔仔  阅读(45)  评论(0编辑  收藏  举报

Prefix sum, 参考这个solution, 讲解的很清楚。

. What is prefix sum

Prefix sum is a sum of the current value with all previous elements starting from the beginning of the structure.

 

图1. Prefix sum for 1D array

 

图2.Prefix sum for 2D array

 

 

 图3. Prefix sum for binary tree

 对于简答的1D array来说我们用一个dictionary "prefix sum -> 目前出现的次数", 然后在for loop 1D array 的过程中, 看prefix sum 是否等于target, 如果是那么count += 1, 另外再加上d[prefixSum - target], 最后更新dictionary。跟[LeetCode] 1. Two Sum_Easy tag: Hash Table 的过程有点类似。

 

 可以解决的lc题目:

 [LeetCode] 560.Subarray Sum Equals K_Medium tag: Array, Subarray, prefix Sum