题目原文:
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]为从头开始偷到第n家获得的钱数,则转移方程如下:
dp[n]=max(dp[n-1],dp[n-2]+money[n])
因为如果不偷第n家,则获得的最大钱数与偷前n-1家获得的钱数相同,如果偷第n家,则第n-1家不能偷,获得的钱数就是前n-2家的最大收益加上第n家里有的钱。
而编码过程中因为dp[n]只与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数组构造的方法以及转移方程的确立。