House Robber - LeetCode 198

题目描述:

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.

分析:有个强盗专业户,想沿一条街抢家劫舍,但是每两个房子之间有防盗系统,如果打劫两个相邻的房子,则会自动报警,那么警察就会把该家伙带走,那么在保证不被警察带走的情况下,强盗应该怎么进行盗窃才能获得最大的钱。设每个房子所含的钱的数目用一个非负的整形数组num[]保存。

该题是一个明显的动态规划问题,在进行下一步时,都在前一个最优解的基础上。

思路:设置一个数组dp[],存放到从前到后的每个节点未知所能获得的最多的钱的数目。

那么在第0户:dp[0] = num[0];

到第1户最大值dp[1]:由于不能访问相邻的元素,那么选择较大者,dp[1] = max{dp[0],num[1]}

到第2户最大值dp[2]:同样不能访问相邻的元素,所以在第0户人家获得的最多数目加上第2户的数目后,与第1户的最大值比较,第2户的最大值为两者中的较大者。即dp[2] = max{dp[1],dp[0]+ num[2]};

...

到第i户人家获得的最大值:dp[i] = max{dp[i-1],dp[i-2]+ num[i]}

以下是C++实现代码:

/**//3ms*/
class Solution {
public:
    int rob(vector<int> &num) {
        if(num.empty())
            return 0;
        vector<int>::size_type n = num.size();
        if(n == 1)
            return num[0];        
        vector<int> dp;
        dp.push_back(num[0]);
        int max = dp[0];
        dp.push_back(dp[0] > num[1] ? dp[0]:num[1]);
        if(dp[1] > max)
            max = dp[1];
        for(vector<int>::size_type i = 2; i != n; i++)
        {
            int k = dp[i-2] + num[i];
            dp.push_back(dp[i-1] > k ? dp[i-1] : k);
            if(max < dp[i])
                max = dp[i];
        }       
        return max;           
    }
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值