解析
题目有点费解,大致应该是给出区间内的和,然后维护一个前缀和,为了防止越界,先填一个0进去,在构建的时候也要注意此时构建的dp的下标是i+1,所以加的前缀和的下标是i。
代码
class NumArray {
public:vector <int> dp;NumArray(vector<int>& nums) {dp.push_back(0);for(int i = 0; i< nums.size(); i++){if(i == 0){dp.push_back(nums[0]);}else{dp.push_back(nums[i] + dp[i]);}}}int sumRange(int left, int right) {return dp[right+1] - dp[left]; }
};/*** Your NumArray object will be instantiated and called as such:* NumArray* obj = new NumArray(nums);* int param_1 = obj->sumRange(left,right);*/