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这个点的特殊情况就可以了 ,代码如下:
class NumArray {
public:
NumArray(vector<int> &nums) {
sum.resize(nums.size());
for(int i = ; i < nums.size(); ++i){
sum[i] = i == ? nums[] : nums[i] + sum[i - ];
}
} int sumRange(int i, int j) {
if(i == )
return sum[j];
return sum[j] - sum[i - ];
}
private:
vector<int> sum;
};