您的位置:首页 > 其它

leetcode 198. House Robber

2017-08-31 10:06 323 查看
原题:

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.
代码如下:
int rob(int* nums, int numsSize) {
if(numsSize==0)
return 0;
if(numsSize==1)
return *nums;
if(numsSize==2)
return *nums>*(nums+1)?*nums:*(nums+1);
if(numsSize==3)
return (*(nums)+*(nums+2))>*(nums+1)?*(nums)+*(nums+2):*(nums+1);
*(nums+2)=(*(nums)+*(nums+2))>*(nums+1)?*(nums)+*(nums+2):*(nums+1);
*(nums+1)=*nums>*(nums+1)?*nums:*(nums+1);
for(int n=3;n<numsSize;n++)
{
*(nums+n)=(*(nums+n-3)>*(nums+n-2)?*(nums+n-3):*(nums+n-2))+*(nums+n);
}
return *(nums+numsSize-1)>*(nums+numsSize-2)?*(nums+numsSize-1):*(nums+numsSize-2);
}使用动态规划的方法,总结出递推公式为sum[i]=max(sum[i-2,sum[i-3]])+i。
开始强行用函数递归的时候超时了,后来去除了各种重复运算以后就ok了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: