[LeetCode] 198. House Robber
Posted CNoodle
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 198. 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.
Example 1:
Input: [1,2,3,1] Output: 4 Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4.
Example 2:
Input: [2,7,9,3,1] Output: 12 Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). Total amount you can rob = 2 + 9 + 1 = 12.
打家劫舍。
你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。
给定一个代表每个房屋存放金额的非负整数数组,计算你 不触动警报装置的情况下 ,一夜之内能够偷窃到的最高金额。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/house-robber
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路是动态规划。因为不能偷相邻的两个房子,所以如果要偷当前某个房子,需要比较的是到底是偷当前房子 + 两个位置前的房子,还是偷一个位置前的房子 + 不偷当前位置的房子。dp[i]的定义是如果偷前i个房子得到的最大收益是多少。
时间O(n)
空间O(n)
Java实现
1 class Solution { 2 public int rob(int[] nums) { 3 // corner case 4 if (nums == null || nums.length == 0) { 5 return 0; 6 } 7 8 // normal case 9 int len = nums.length; 10 int[] dp = new int[len + 1]; 11 dp[0] = 0; 12 dp[1] = nums[0]; 13 for (int i = 2; i <= len; i++) { 14 dp[i] = Math.max(dp[i - 2] + nums[i - 1], dp[i - 1]); 15 } 16 return dp[len]; 17 } 18 }
Java空间O(1)实现
注意几个变量的定义,prev = dp[i - 2], cur = dp[i -1],所以对于每一个位置上的house,如果偷的话,就计算到底是cur大还是prev + nums[i]大
1 class Solution { 2 public int rob(int[] nums) { 3 // corner case 4 if (nums == null || nums.length == 0) { 5 return 0; 6 } 7 8 // normal case 9 // prev = dp[i - 2], cur = dp[i - 1] 10 int prev = 0; 11 int cur = 0; 12 for (int num : nums) { 13 int temp = Math.max(cur, prev + num); 14 prev = cur; 15 cur = temp; 16 } 17 return cur; 18 } 19 }
以上是关于[LeetCode] 198. House Robber的主要内容,如果未能解决你的问题,请参考以下文章