标签:
题目: 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做。用dp做的时候脑子里想了这些:
1. state:我们用f(i) 表示在第i户,我们能抢到的最多的钱。
2. function:f(i) = max(f(i - 2) + Mi, f(i - 1)). 原因是,如果连续强两个,人家就报警了~
3. initialize: f(0) = num[0] , f(1) = max(num[0], num[1]); 在这里我出了bug,没有考虑对于f(1)取最大值,无脑初始化了。
4. return f(1)
1 public int rob(int[] num) { 2 if (num == null || num.length == 0) { 3 return 0; 4 } 5 if (num.length == 1) { 6 return num[0]; 7 } 8 if (num.length == 2) { 9 return Math.max(num[0], num[1]); 10 } 11 int[] sum = new int[2]; 12 sum[0] = num[0]; 13 sum[1] = Math.max(num[1], num[0]); 14 for (int i = 2; i < num.length; i++) { 15 int temp = Math.max(sum[0] + num[i], sum[1]); 16 sum[0] = sum[1]; 17 sum[1] = temp; 18 } 19 return sum[1]; 20 }
标签:
原文地址:http://www.cnblogs.com/gonuts/p/4395245.html