【leetcode】198. House Robber

来源:互联网 发布:虚拟币场外交易源码 编辑:程序博客网 时间:2024/06/13 16:20

一、题目描述

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.


题目解读:一个小偷入房盗窃,不能同时偷两个连在一起的房间,否则会报警


思路:动态规划问题,对于第 i  个房间有两种策略,一种是盗窃一种是不盗窃。设置一个数组dp[i] 代表在第 i 个房子时达到的最大的收益。那么对于dp[i]有两种计算:

(1)如果盗窃第 i 个房子,那么对于第 i-1 个房子肯定是不盗窃的,因此dp[i] = dp[i-2] + nums[i]

(2)如果不盗窃第 i 个房子,那么dp[i] = dp[i-1]

所以dp[i] = max(dp[i-2]+nums[i], dp[i-1])


c++代码(0ms,18.62%)

class Solution {public:    int rob(vector<int>& nums) {        int len=nums.size();        if(len==0)            return 0;        int *dp=new int[len];        dp[0]=nums[0];        dp[1]=max(dp[0], nums[1]);        for(int i=2; i<len; i++){            dp[i] = max(dp[i-1], dp[i-2]+nums[i]);        }        return dp[len-1];    }};




0 0
原创粉丝点击