leetcode-DP- 303. Range Sum Query – Immutable
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.
DP解法,先计算0-第i项的和,最终结果就是0-j的和减去0-i-1的和
class NumArray {
public:
vector<int> sums;
int s;
NumArray( vector<int> nums)
{
s = nums.size();
if (s <= 0)return ;
sums.reserve(100);
sums.push_back(nums[0]);
for (int i = 1; i < nums.size(); i++)
{
int a = sums[i - 1] + nums[i];
sums.push_back(a);
}
}
int sumRange(int i, int j) {
if (s <= 0)return 0;
if (i == 0)return sums[j];
return sums[j]-sums[i-1];
}
};