leetcode 198. House Robber

来源:互联网 发布:琉璃神社app备用域名 编辑:程序博客网 时间:2024/06/14 21:25

原题:

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了。

原创粉丝点击