前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【Leetcode 198】关关的刷题日记69 – Leetcode 198 House Robber

【Leetcode 198】关关的刷题日记69 – Leetcode 198 House Robber

作者头像
WZEARW
发布2018-04-12 09:59:51
4690
发布2018-04-12 09:59:51
举报
文章被收录于专栏:专知专知

关关的刷题日记69 – 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.

题目的意思是小偷沿着一排街道抢劫房子,每个房子都有一定数额的钱,但是不可以抢相邻的房子,问可以抢到的最大的钱数。

思路

动态规划的题目:设re[i]是抢劫前i个房子获得的最大收益,那么可以分为第i个房子不被抢和第i个房子被抢两种情况:第i个房子不被抢,re[i]=re[i-1];第i个房子被抢,re[i]=re[i-2]+nums[i];状态转移方程re[i]=max(re[i-1], re[i-2]+nums[i])。

代码语言:javascript
复制
class Solution {public:
    int rob(vector<int>& nums) {
        int n=nums.size();
        if(n==0)
            return 0;
        if(n==1)
            return nums[0];
        if(n==2)
            return max(nums[0], nums[1]);
        int temp1=nums[0], temp2=max(nums[0],nums[1]), re;
        for(int i=2; i<n; i++)
        {
            re=max(temp1+nums[i],temp2);
            temp1=temp2;
            temp2=re;
        }
        return re;
    }};

以上就是关关关于这道题的总结经验,希望大家能够理解,有什么问题可以在我们的专知公众号平台上交流或者加我们的QQ专知-人工智能交流群 426491390,也可以加入专知——Leetcode刷题交流群(请先加微信小助手weixinhao: Rancho_Fang)。

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2017-12-18,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 专知 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目
  • 思路
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档