您的位置:首页 > 其它

leetcode 198. House Robber

2017-08-18 17:24 447 查看
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.
这道题是典型的DP题。

public int rob(int[] nums) {
int n=nums.length;
if(n==0){
return 0;
}
//dp[i]:存储i~num.length能偷的最大钱
int[] dp=new int[n+1];
dp
=0;
dp[n-1]=nums[n-1];
for(int i=n-2;i>=0;i--){
//不偷i,再从i+1开始偷,或者偷i,再从i+2开始偷
dp[i]=Math.max(dp[i+1], nums[i]+dp[i+2]);
}
return dp[0];
}
大神也用的DP,不过跟我的有点不一样。

public int rob(int[] num) {
int[][] dp = new int[num.length + 1][2];
for (int i = 1; i <= num.length; i++) {
dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1]);
dp[i][1] = num[i - 1] + dp[i - 1][0];
}
return Math.max(dp[num.length][0], dp[num.length][1]);
}

dp[i][1] means we rob the current house(i-1 house) and dp[i][0] means we don't,
so it is easy to convert this to O(1) space.

public int rob(int[] num) {
//max monney can get if rob current house
int rob = 0;
//max money can get if not rob current house
int notrob = 0;
for(int i=0; i<num.length; i++) {
//if rob current value, previous house must not be robbed
int currob = notrob + num[i];
//if not rob ith house, take the max value of robbed (i-1)th house and not rob (i-1)th house
notrob = Math.max(notrob, rob);
rob = currob;
}
return Math.max(rob, notrob);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: