Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
Example:
Given nums = [-2, 0, 3, -5, 2, -1]
sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3
Note:
You may assume that the array does not change.
There are many calls to sumRange function.
解法: Memorization/DP with O(1) time and O(N) space
就是Subarray类题目的变形,求subarray sum首先要想到前缀和数组。维护一个cumulative sum,然后每次计算i到j的和的时候就是sum[j] - sum[i-1],花费时间是O(1)要注意的是下边界越界的处理。
dp[i] = (k - 1) * (dp[i -1] + dp[i - 2])