leetCode 303. Range Sum Query - Immutable | Dynamic Programming

303. Range Sum Query - Immutable 數組

Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.ide

Example:
spa

Given nums = [-2, 0, 3, -5, 2, -1]

sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3


Note:
orm

  1. You may assume that the array does not change.element

  2. There are many calls to sumRange function.it

題目大意:求數組一個連續子集的和。io

思路:table

1.能夠直接找到數組子集的起始位置,連續相加到終止位置,function

就能夠獲得答案。這樣的話,沒計算一次都要連續相加,比較麻煩。因此想到下面的思路。class

2.用一個數組來存放當前元素的以前元素的和。

例如:

vector<int> source,源數組

vector<int> preITotal,用來存放source前i個元素的和,包括第i個元素。

之後每次計算範圍源數組[i,j]範圍子集的和,preITotal[j] - preITotal[i-1].計算便可。



代碼以下:

class NumArray {
private:
    vector<int> preITotal;//存放前i個元素的和
public:
    NumArray(vector<int> &nums) {
        if(nums.empty())
            return;
        preITotal.push_back(nums[0]);
        for(int i = 1; i < nums.size(); ++i)
            preITotal.push_back(preITotal[i-1] + nums[i]);
    }

    int sumRange(int i, int j) {
        if(0 == i)
            return preITotal[j];
        return preITotal[j] - preITotal[i - 1];
    }
};


// Your NumArray object will be instantiated and called as such:
// NumArray numArray(nums);
// numArray.sumRange(0, 1);
// numArray.sumRange(1, 2);

總結:

題目標註爲動態規劃,開始怎麼也想不出哪裏用到動態規劃的思想了。當把當前的結果記錄下來,之後使用這一點,和動態規劃掛鉤了。


2016-08-31 22:42:39

相關文章
相關標籤/搜索