题目
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.
解答
这道题目是一道很简单的动态规划问题中的子结构重复问题,主要在于sumRange()中如何计算;这里我采用先将所有(0,i);i <nums.size()
的子集储存在acc数组中,然后所有的计算都可以直接调用acc 数组相减完成计算;
具体代码如下:
class NumArray {
public:
NumArray(vector<int> nums) {
accu.push_back(0);
for (iter = nums.begin(); iter != nums.end(); iter++)
accu.push_back(accu.back() + *iter);
}
int sumRange(int i, int j) {
return accu[j + 1] - accu[i];
}
private:
vector<int> accu;
vector<int>::iterator iter;
};