标签:ted sys 空间 int col cal eterm min 位置
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.
打家劫舍。题意是你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。给定一个代表每个房屋存放金额的非负整数数组,计算你 不触动警报装置的情况下 ,一夜之内能够偷窃到的最高金额。
思路是动态规划。因为不能偷相邻的两个房子,所以如果要偷当前某个房子,需要衡量的是到底是偷当前房子 + 两个位置前的房子,还是偷一个位置前的房子。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 }
标签:ted sys 空间 int col cal eterm min 位置
原文地址:https://www.cnblogs.com/cnoodle/p/12985265.html