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.

题目链接

题意:

假设是一个小偷(这比喻,,,),在这条街上有一排房子,每一个房子都有一个确定的价值,相邻的房子不能连续偷窃,问,偷了这条街后,最大偷窃的价值总和是多少?

利用DP思想,对于从第4个房子开始,有两种选择,偷或不偷,假如不偷,则集成上一个房子的价值,假如偷,那么再从隔一个的还是隔两个的两个之间选择一个最大的加上这一个房子的价值,核心式是:

dp[i] = max(dp[i-1], max(dp[i-2], dp[i-3]) + nums[i]);

同时更新ans,因为每一个房子的dp值都是目前看来最大的,所以只需要判断隔一天和隔两天即可,三天及以上就不是最大值了。

代码如下:

class Solution {
public:
    int dp[11111];
    
    int rob(vector<int>& nums) {
        if (nums.empty()) return 0;
        else if (nums.size() == 1) return nums[0];
        else if (nums.size() == 2) return max(nums[0], nums[1]);
        else if (nums.size() == 3) return max(nums[0]+nums[2], nums[1]);
        int ans = nums[0];
        dp[0] = nums[0];
        dp[1] = nums[1];
        dp[2] = max(dp[0]+nums[2], dp[1]);
        
        for (int i = 3; i < nums.size(); i ++) {
            dp[i] = max(dp[i-1], max(dp[i-2], dp[i-3]) + nums[i]);
            ans = max(ans, dp[i]);
        }
        return ans;
    }
};


呃。。看了下最优解,果然也是dp,不过比我这种思路更为简单(写的时候没改出来,以为不正确,,,还是太菜),对于每个房子而言,都有两种选择,偷或则不偷,不偷的话,结果同上一个房子,假如偷,那么结果就是nums[i] + dp[i-2],最终在两个选择种选择较大的。

代码如下:

class Solution {
public:
    int dp[11111];
    
    int rob(vector<int>& nums) {
        if (nums.empty()) return 0;
        else if (nums.size() == 1) return nums[0];
        else if (nums.size() == 2) return max(nums[0], nums[1]);
        int ans = nums[0];
        dp[0] = nums[0];
        dp[1] = max(dp[0], nums[1]);
        
        for (int i = 2; i < nums.size(); i ++) {
            dp[i] = max(dp[i-1], dp[i-2] + nums[i]);
            ans = max(ans, dp[i]);
        }
        return ans;
    }
};
第一次没改出来的原因在第 dp[1] 的赋值上,dp[1] 应该是在前两个种选择大者,这样才能保证在之后的运算中,保证加到的dp一定是最大的。


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值