[LeetCode 198] House Robber(动态规划)

题目内容

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.
Credits:
Special thanks to @ifanchu for adding this problem and creating all test cases. Also thanks to @ts for adding additional test cases.

题目简述

在一维数组中找出不相邻的数字组合总和的最大值

题目分析

对于每一个数字,有两种情况,选或不选;若选择该数,和为不选择之前数字的最大值加上该数的值。否则和为选择或不选择之前的数的最大值。显然为动态规划问题。
进一步分析,使用一个二维数组A[n][2]来记录每次选择之后的总和,n为数组大小。
A[i][0]表示不选择第i个数的最大值,A[i][1]表示选择第i个数的最大值,从头开始遍历原数组并维护该二维数组,最后结果即为数组最后一列两数的最大值。设原数组为nums[n],数组第i列计算方法如下(假设此时该列右边的列已计算):
**A[i][0]=max(A[i-1][0],A[i-1][1]),
A[i][1]=A[i-1][0]+nums[i].**
实际编程时,观察到上式中二维数组第i列的值只与第i-1列的值有关,每次遍历只需不断根据上式更新两个变量的值,储存A[i-1][0],A[i-1][1]的值即可。

代码示例

int rob(vector<int>& nums) {
        int n=nums.size();
        int temp;
        int best0=0;
        int best1=0;
        for(int i=0;i!=n;i++)
        {
            temp=best0;
            if(best1>best0) best0=best1;
            best1=temp+nums[i];
        }
        if(best0>best1) return best0;
        else return best1;  
    }

时间复杂度O(n),空间复杂度O(1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值