House Robber

题目名称
House Robber—LeetCode链接

描述
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.

分析
  题目中已经给了提示dynamic programming,说明这道题是动态规划问题。
  在准备抢第N个房间时,保留两个数:经过第N-1个房间抢到的最多钱数和经过N-2个房间抢到的最多钱数。那么对于当前的房间N,有两个选择:
(1) 如果抢,则第N-1个房间不能抢,此时抢到的最多钱数为rob(N)=rob(N-2)+money(N);
(2) 如果不抢,rob(N) = rob(N-1),给一个例子:
(3) 判断下(1)(2)中哪种方式抢到的钱多,即为rob(N)。
这里写图片描述
经过第1个房间时,rob(1) = 4;
经过第2个房间时,因为6>4,rob(2) = 6;
经过第3个房间时,因为rob(1)+8>rob(2),则rob(3)=12;
经过第4个房间时,因为rob(2)+10>rob(3),则rob(4)=16;
经过第5个房间时,因为rob(3)+12>rob(4),则rob(5)=24;
经过第6个房间时,因为rob(4)+48>rob(5),则rob(6)=64;
经过第7个房间时,因为rob(5)+20

/**************************************************************

Copyright:武汉大学计算机学院B507

Author: Ryan

Date:2015-10-22

Description:按照给定模式切割字符串

**************************************************************/
#include<iostream>
#include<vector>
using namespace std;

int rob(vector<int>& nums) {
    int n = nums.size();
    if(n==0)
        return 0;
    if(n==1)
        return nums[0];  
    //定义两个变量,一个保存到当前房间偷取的最大钱数,一个是到上一个房间偷取的最大钱数      
    int prev,cur;
    //初始化操作,到了第二个房间时,prev=num[0];cur=nums[0]>nums[1]?nums[0]:nums[1]; 
    prev=nums[0];
    if(nums[1]<nums[0])
        cur = nums[0];  
    else
        cur = nums[1];
    //动态规划开始,每次都计算一下对于当前房间偷或者不偷能得到的最大钱数  
    for(int i=2;i<n;i++){
        int temp=cur;
        if(cur<prev+nums[i]){
            cur = prev+nums[i];
        }
        prev = temp;
    }
    return cur;
}

int main(){
    int a[9] = {4,6,8,10,12,48,20,19,37};
    vector<int> money(a,a+9);
    for(int i=0;i<money.size();i++)
        cout<<money[i]<<" ";
    cout<<endl;

    int total = rob(money);
    cout<<total;
    return 0;
}

总结
  小弟第一次写动态规划的文章,也是第一次系统学习动态规划,也希望多做几个练习来加强对动态规划问题的理解和感悟。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值