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.
class NumArray {
public:
NumArray(vector<int> &nums) {
mNums=nums;
sums = new vector<int>(nums.size()+1);
(*sums)[0] = 0;
for(int i=1;i<nums.size()+1;i++){
(*sums)[i]=(*sums)[i-1]+n ums[i-1];
}
}
int sumRange(int i, int j) {
return (*sums)[j+1]-(*sums)[i];
}
private:
vector<int> mNums;
vector<int>* sums;
};
House Robber
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.
解法1:存储到每间屋子为止是否抢劫能获得的最优资金。
int rob(vector<int>& nums) {
if(nums.size() == 0)
return 0;
int rob = nums[0], notRob = 0;
for(int i = 1; i < nums.size(); i++){
int tmp = notRob;
notRob = max(notRob, rob);
rob = tmp + nums[i];
}
return max(notRob, rob);
}
解法2:a,b分别记录前两个屋子和前一个屋子为止能获得的最大收益。
int rob(vector<int>& nums) {
int a = 0;
int b = 0;
for (int i=0; i<nums.size(); i++)
{
if (i%2==0) a = max(a+nums[i], b);
else b = max(a, b+nums[i]);
}
return max(a, b);
}
Climbing Stairs
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
one记录前一台阶的走法,two记录前两台阶的走法。当前的台阶的走法为one+two;对于下一台阶而言,前两台阶走法为one,前一台阶走法为cur。 int climbStairs(int n) {
if(n < 2) return 1;
int cur;
int one = 1,two = 1;
for(int i = 2; i < n + 1; i++){
cur = one + two;
two = one;
one = cur;
}
return cur;
}