较简单的动态规划题目:LeetCode 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.
其实最简单的思路就是将所要求的区域内的数字相加,不过这样频繁调用会使得复杂度较大。
采用动态规划的思路,只调用一次构造函数即可。这样一来sumRange函数的复杂度降为O(1)。
class NumArray {
public:
vector<int> sum;
NumArray(vector<int> nums) {
sum.push_back(0);
for (int i = 1; i <= nums.size(); i++) {
sum.push_back(sum[i - 1] + nums[i - 1]);
}
}
int sumRange(int i, int j) {
return sum[j + 1] - sum[i];
}
};