标签:sam == ann 表示 cer ping ota rmi tomat
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.
一上来就想到用递归的方法,思路很简单如果数组长度为1,则返回该元素,如果数组长度为2,则返回两个中的较大值,然后直接进行递归即可。然而很不幸,这种方法超时了!!!!!!!但是还是把代码放在这里吧。
class Solution {
public int rob(int[] nums) {
if(nums.length ==0 ) return 0;
if(nums.length == 1) return nums[0];
if(nums.length == 2) return nums[0] > nums[1] ? nums[0] : nums[1];
return Math.max((nums[0] + rob(Arrays.copyOfRange(nums, 2, nums.length))),(nums[1] + rob(Arrays.copyOfRange(nums, 3, nums.length))));
}
}
用动态规划(dp)来求解,用dp[i]表示以nums[i]为偷的最后一间屋子时,能偷的最大财富。
状态边界:dp[0] = nums[0], dp[1] = max(nums[0], nums[1])
状态转移方程:dp[i] = max(dp[i-1],di[i-2]+nums[i]);
时间复杂度和空间复杂度都为O(n)
class Solution {
public int rob(int[] nums) {
if(nums.length == 0) return 0;
if(nums.length == 1) return nums[0];
int[] dp = new int[nums.length];
dp[0] = nums[0];
dp[1] = Math.max(nums[0], nums[1]);
for(int i = 2; i < nums.length; i++) {
dp[i] = Math.max((dp[i-2] + nums[i]),dp[i-1]);
}
return dp[nums.length-1];
}
}
然后可以进一步把空间复杂度降为O(1),思路和动态规划是一样的。
public class Solution {
public int rob(int[] num) {
int last = 0;
int now = 0;
int tmp;
for (int n :num) {
tmp = now;
now = Math.max(last + n, now);
last = tmp;
}
return now;
}
}
标签:sam == ann 表示 cer ping ota rmi tomat
原文地址:https://www.cnblogs.com/shinjia/p/9776125.html