[LeetCode]House Robber
2015-04-06 17:31 庸男勿扰 阅读(251) 评论(0) 编辑 收藏 举报原题链接:https://leetcode.com/problems/house-robber/
题意描述:
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.
题解:
这道题的目标是从一个数组中选出一个子集,使得和最大,约束是选出的子集不能有在原来数组中相邻的。很明显这种求最优的一般都是要往动态规划上靠。
具体的状态转移可表述为,当到了第i个数时,有两个选择,选或者不选,假设如果选,那么最优值为dp1,不选,最优值为dp0,那么很显然
dp0 = max(dp1,dp0),即上一步选或者不选的最优值中的较大值;
dp1 = dp0+val[i],注意,这里的dp0不是上一行的dp0,而是指上一个状态中的不选的最优值,因为只有上一个不选,当前这个才能选。
找到这个那么代码就很简单了。
具体代码如下:
1 public class Solution { 2 public int rob(int[] num) { 3 int dp0 = 0; 4 int dp1 = 0; 5 for (int i = 0; i < num.length; i++) { 6 int tmp = dp0; 7 dp0 = Math.max(dp1, dp0); 8 dp1 = tmp+num[i]; 9 } 10 return Math.max(dp0, dp1); 11 } 12 }
出处:http://www.cnblogs.com/codershell
本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
如果您觉得对您有帮助,不要忘了推荐一下哦~