DP (1) -- Range Sum Query - Immutable, House Robber, Climbing Stairs

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:

  1. You may assume that the array does not change.
  2. There are many calls to sumRange function.
range sum采用end与start的和做减的方式计算。

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;
    }



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值