198. House Robber(入室强盗)

来源:互联网 发布:矩阵论教程 pdf 编辑:程序博客网 时间:2024/04/29 01:08

标签(空格分隔): leetcode dp


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.
题意:
1. 每间房屋藏有一定的钱
2. 阻止你们抢劫每个人的唯一约束是邻近的房屋有安全系统连接,
3. 如果两个相邻的房屋在同一天晚上被打破,它将自动联系警察。
4. 给出一个代表每个房子的非负整数的钱的列表,确定你今天晚上可以抢救的最大金额,而不用警报。

思路;
状态转移方程:
dp[0] = num[0] (当i=0时)
dp[1] = max(num[0], num[1]) (当i=1时)
dp[i] = max(num[i] + dp[i - 2], dp[i - 1]) (当i !=0 and i != 1时)

当数只有0,1,2这大小的时候,直接计算,然后如果大于2个数,我们就可以分解成三部分,每次计算最左边最大值和最右边的数的和与中间的最大值比较;

int rob(vector<int>& nums) {    if (nums.empty()){return 0;}    int len = nums.size();    if (len == 1) return nums[0];    if (len == 2) return nums[0]>nums[1]?nums[0]:nums[1];    int i = 2;    int ans = 0;    int left = nums[0], mid = max(nums[0],nums[1]);    for (i; i < len;++i)    {        ans = max(nums[i] +left, mid);        left = mid;        mid = ans;    }    return ans;}

别人的做法:

class Solution {public:    int rob(vector<int>& nums) {        int numsSize = nums.size();        int a = 0, b = 0;        for(int i=0; i<numsSize; i++){            if(i%2==0)                a = max(a+nums[i],b);            else                b = max(b+nums[i],a);        }        return max(a,b);    }};

设置奇偶校验,交替计算前n项的最大值;

原创粉丝点击