Easy-题目26:198. House Robber
2016-05-30 20:11
316 查看
题目原文:
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.
题目大意:
你是一个专业的小偷,计划偷取一条街上的房子。每一个房子内有确定数量的钱,但每两间房子之间连有警报器,如果两个相邻的房子都被偷了,则警报器报警。
用一个数组代表每间房子里拥有的钱数,求出小偷在不引发警报的情况下获得的最大钱数。
题目分析:
一个很简单的DP问题。设dp
为从头开始偷到第n家获得的钱数,则转移方程如下:
dp
=max(dp[n-1],dp[n-2]+money
)
因为如果不偷第n家,则获得的最大钱数与偷前n-1家获得的钱数相同,如果偷第n家,则第n-1家不能偷,获得的钱数就是前n-2家的最大收益加上第n家里有的钱。
而编码过程中因为dp
只与n-1和n-2两项有关系,所以只需要保留两个变量,而不需开一个长度为n的数组。
源码:(language:c)
成绩:
0ms,beats3.60%,众数0ms,96.40%
Cmershen的碎碎念:
本题应该是从第一题以来第一道用dp解决的题目。以后遇到dp的题要多注意,多考虑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.
题目大意:
你是一个专业的小偷,计划偷取一条街上的房子。每一个房子内有确定数量的钱,但每两间房子之间连有警报器,如果两个相邻的房子都被偷了,则警报器报警。
用一个数组代表每间房子里拥有的钱数,求出小偷在不引发警报的情况下获得的最大钱数。
题目分析:
一个很简单的DP问题。设dp
为从头开始偷到第n家获得的钱数,则转移方程如下:
dp
=max(dp[n-1],dp[n-2]+money
)
因为如果不偷第n家,则获得的最大钱数与偷前n-1家获得的钱数相同,如果偷第n家,则第n-1家不能偷,获得的钱数就是前n-2家的最大收益加上第n家里有的钱。
而编码过程中因为dp
只与n-1和n-2两项有关系,所以只需要保留两个变量,而不需开一个长度为n的数组。
源码:(language:c)
int rob(int* nums, int numsSize) { if(numsSize==0) return 0; if(numsSize==1) return nums[0]; else if(numsSize==2) return nums[0]>nums[1]?nums[0]:nums[1]; else { int i; int dp1,dp2,dp; dp1=nums[0]; dp2=nums[0]>nums[1]?nums[0]:nums[1]; for(i=2;i<numsSize;i++) { dp=dp2>dp1+nums[i]?dp2:dp1+nums[i]; dp1=dp2; dp2=dp; } return dp; } }
成绩:
0ms,beats3.60%,众数0ms,96.40%
Cmershen的碎碎念:
本题应该是从第一题以来第一道用dp解决的题目。以后遇到dp的题要多注意,多考虑dp数组构造的方法以及转移方程的确立。
相关文章推荐
- 沙盒路径
- 2015北大夏令营day1 B:An Idea of Mr. A
- 抽象类和接口
- IDEA 安装与设置
- 字符集乱码决绝大全
- iscc2016-basic-find-to-me
- Easy-题目25:101. Symmetric Tree
- zsh的自动完成辅助工具:oh-my-zsh
- 天注定--从现在开始的展望
- SNMP++ 04-SNMP中OBJECT IDENTIFIER的BER编码与解码及一些思考
- Easy-题目24:110. Balanced Binary Tree
- 基因数据处理42之mango问题_seqdict.avro不存在解决
- Intent中的四个重要属性——Action、Data、Category、Extras
- 第二阶段团队项目冲刺站立会议(七)
- 51nod算法马拉松14
- Easy-题目23:21. Merge Two Sorted Lists
- 剑指offer-java(4)
- [JavaScript] 10.JS 表单操作
- 宏、函数、宏函数,内联函数的区别
- Easy-题目22:231. Power of Two