原题链接:
https://leetcode.com/problems/house-robber/
https://leetcode.com/problems/house-robber-ii/
第一题题意是一个贼要偷东西,有n户人家,如果偷相邻两家,就会触发警报。警报一响,警察来抓,逮走(做贼不容易啊)。问怎样在不触发警报而偷走最多的钱。
第二题在第一题基础上有加了个收尾相连,即偷了第一家不能偷最后一家,偷了最后一家不能偷第一家。
很明显用动态规划解题。
之前不了解动态规划的同学,可以先看背包问题九讲!!!,讲的很好,之后我也回把背包问题的代码贴出来。本来想自己写一个系列,想想不重复早轮子了。
背包问题九讲链接地址:http://love-oriented.com/pack/(必看)
第一题:
package leetcode; public class HouseRobber { public static int rob(int[] nums) { // https://leetcode.com/problems/house-robber/ /** * 你是一名专业强盗,计划沿着一条街打家劫舍。 每间房屋都储存有一定数量的金钱,唯一能阻止你打劫的约束条件就是:由于房屋之间有安全系统相连 * 如果同一个晚上有两间相邻的房屋被闯入,它们就会自动联络警察,因此不可以打劫相邻的房屋。 */ if (nums == null || nums.length == 0) { return 0; } int len = nums.length; int[] max = new int[len]; max[0] = nums[0]; for (int i = 1; i < len; i++) { if (i <= 1) { max[i] = Math.max(nums[i], max[i - 1]); } else { max[i] = Math.max(max[i - 1], max[i - 2] + nums[i]); } } return max[len - 1]; } public static void main(String[] args) { // TODO Auto-generated method stub int[] nums = new int[] { 1, 3, 1 }; System.out.println(rob(nums) + ""); } }第二题:
因为收尾相邻,所以分两种情况,第一种情况是从第一个到倒数第二家进行第一题的方法进行计算最大值,第二种情况时从第二家到倒数第一家进行第一题的方法进行计算最大值,这样最后一家与第一家就不会同时选到了。最后求两者最大值,就是最终结果了。
package leetcode; public class HouseRobberII { public static int rob(int[] nums) { // https://leetcode.com/problems/house-robber-ii/ if (nums == null || nums.length == 0) { return 0; } int len = nums.length; if (len == 1) { return nums[0]; } if (len == 2) { return Math.max(nums[0], nums[1]); } int first = robi(nums, 0, len - 2); int last = robi(nums, 1, len - 1); return Math.max(first, last); } // HouseRobber1改写 private static int robi(int[] nums, int start, int end) { int len = end - start + 1; int[] res = new int[len]; res[0] = nums[start]; for (int i = 1; i < len; i++) { if (i <= 1) { res[i] = Math.max(nums[start+i], res[i - 1]); } else { res[i] = Math.max(res[i - 2] + nums[start+i], res[i - 1]); } } return res[len - 1]; } public static void main(String[] args) { // TODO Auto-generated method stub int[] nums = new int[] { 1, 2, 1, 1 }; System.out.println(rob(nums) + ""); } }