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了。
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了。
相关文章推荐
- Leetcode——198. House Robber
- 【LeetCode】198. House Robber
- LeetCode 198. House Robber (动态规划)
- LeetCode:198. House Robber
- LeetCode 198. House Robber
- [LeetCode]198. House Robber
- LeetCode 198. House Robber(java)
- Leetcode 198. House Robber
- leetcode 198. House Robber
- LeetCode 198. House Robber
- 【Leetcode】198. House Robber - - 【动态规划】
- leetcode 198. House Robber
- LeetCode 198. House Robber
- LeetCode 198. House Robber
- leetcode198. House Robber
- LeetCode 198. House Robber【DP+滚动数组】
- Leetcode-198. House Robber,213. House Robber II
- 【leetcode】198. House Robber
- Leetcode 198. House Robber
- 【LeetCode】 198. House Robber