您的位置:首页 > 其它

【LeetCode】House Robber 解题报告

2016-05-01 21:47 288 查看

House Robber

[LeetCode]

https://leetcode.com/problems/house-robber/

Total Accepted: 67398 Total Submissions: 196356 Difficulty: Easy

Question

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.

Ways

这种找最大最小值的问题,往往就是利用动态规划!!

动态规划的思想:维护一个dp[],每个元素时遍历原数组时能在i处取得的最大值。此处元素应该由状态转移方程决定。

最终要的就是这个状态转移方程。以及dp[]的初始化元素。

这个题目中,在遍历数组的时候,无非就是这么想:这个房子该不该偷?这么决定的因素是这个房子偷了的话的收益和不偷留着偷下一个房子的收益那个比较高?

略微写了个表:

nums:   1   4   2   1   6   4   3
dp:   1   4   4   5   10  10  13


也就是说比较这个房子和前前个dp的值的和与前个dp哪个值更大。

所以:

dp[0] = num[0] (当i=0时)

dp[1] = max(num[0], num[1]) (当i=1时)

dp[i] = max(num[i] + dp[i - 2], dp[i - 1]) (当i !=0 and i != 1时)

public class Solution {
public int rob(int[] nums) {
if(nums.length==0) return 0;
if(nums.length==1) return nums[0];
int[] maxMoney=new int[nums.length];
maxMoney[0]=nums[0];
maxMoney[1]=Math.max(nums[0],nums[1]);
for(int i=2; i<nums.length; i++){
maxMoney[i]=Math.max(nums[i]+maxMoney[i-2], maxMoney[i-1]);
}
return maxMoney[nums.length-1];
}
}


AC:0ms

其实可以优化空间复杂度。不优化了。嗯。

Date

2016/5/1 21:44:42
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode