LeetCode 198. 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.

这类题目的分析如下:分析时一定要找到固定一点进行分析,否则无从下手。那么我们沉着应对,以任一点i为例(一般分析时以中间值分析为好,边界值等特殊情况可能不便于分析)。我们到任一家所抢的钱的最大数,分两种情况,抢了上家不抢这家,上家没抢必抢这家,取这两个值中的最大值。因为我们到每家都是选取最优的策略,所以抢到最后即是能获得的最大的收获。代码如下:

class Solution {
public:
    int search(int i,vector<int>& nums)
    {
        if(i<0)
        return 0;
        return max(nums[i]+search(i-2,nums),search(i-1,nums));
    }
    int rob(vector<int>& nums) {
        int n=nums.size();
        if(n<=0)return 0;
        int f[n+1];
        f[0]=0;
        f[1]=nums[0];
        for(int i=2;i<n+1;i++)
        {
            f[i]=max(nums[i-1]+f[i-2],f[i-1]);
        }
        return f[n];
    }
};
      上述用递归从后往前递归,由于有冗余所以超时。

      超时:一般出现这种情况就是算法过于复杂,操作次数过多。这时需要稍微更改计算规则。这次是从前往后计算,保存计算值。那么只用计算一次。之前遇到过队列的操作,也是很频繁的push和pop,结果超时。后来使用数组来进行相关交换操作,就通过了。

      编译错误:这是自己要通过编辑器来调试好的。像很多不调试的程序运行出现莫名其妙的问题,很可能就是代码中哪里出现错误。比如数组越界等。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值