leetcode 198. House Robber | 动态规划

Description

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.

My solution

下面的代码是看了discuss的思路之后, 自己又写的. 实际上也是不work的, 并且在提交之前自己就发现了, 但是没有想到解决方案.
其实主要是第0,1 位置点导致了结果不准确: 下方代码是先赋值, 也就是evenmax已经认为略过了i=0的候选, 正确做法是evenmax也从i=0位置开始赋值, 通过max(even, odd)的动态优化方式进行下去.

class Solution {
public:
    int rob(vector<int> &nums) {
        if(nums.size()==1) return nums[0];
        int oddmax = nums[0];
        int evenmax = nums[1];
        for (int i = 2; i < nums.size(); i++) {
            if (i % 2 == 0) {
                oddmax = max(evenmax, oddmax + nums[i]);
            } else {
                evenmax = max(oddmax, evenmax + nums[i]);
            }
        }
        return max(oddmax,evenmax);
    }
};

Discuss

#define max(a, b) ((a)>(b)?(a):(b))
int rob(int num[], int n) {
    int a = 0;
    int b = 0;

    for (int i=0; i<n; i++)
    {
        if (i%2==0)
        {
            a = max(a+num[i], b);
        }
        else
        {
            b = max(a, b+num[i]);
        }
    }

    return max(a, b);
}

重新思考:
这里只用了两个变量a, b就实现了保留历史最优的思路. 和求序列中”最大子序列和”的做法如出一辙. 为什么是两个变量呢? 因为相邻不能同时rob, 对于一个序列{1,2,3,4,5,6}为例, 设想指针游标从左到右开始遍历, 当指向1时, 无法决策最优效果是否选1; 当指向2时, 最优决策可能有1无2, 也可能有2无1; 当指向3时, 仍然是前面所描述的情况, 因为有3必选1, 仍然是有1无2, 而无3必选2. 所以额外利用两个变量, 即可以存储当前最优的情况, 剩下的就是每次max(…)即可动态的让最优始终保持最优.
借助奇偶判断很好的实现了两个最优的继续向前.(注意奇偶和两个!)

Reference

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值