leetcode 198. House Robber

xiaoxiao2021-02-28  143

原题:

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

转载请注明原文地址: https://www.6miu.com/read-23499.html

最新回复(0)