leetcode--House Robber

来源:互联网 发布:淘宝的运费险是什么意思 编辑:程序博客网 时间:2024/05/17 07:51

题目: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.

分析:本质是在一列数组中取出一个或多个不相邻数,使其和最大。一般使用动态规划的方法。方法分为使用一种数组或两个变量或分奇偶

One:基于数组的DP:

public class Solution {    public int rob(int[] nums) {         if(nums.length <= 1)return nums.length==1 ? nums[0] : 0;        int len = nums.length;        int[] dp = new int[len];        dp[0] = nums[0];        dp[1] = Math.max(nums[0],nums[1]);                for(int i=2;i<len;++i){            dp[i] = Math.max(nums[i]+dp[i-2],dp[i-1]);        }        return dp[len-1];           }}
Two:基于两个数的DP--奇偶保证两数不相邻

public class Solution {    public int rob(int[] nums) {        int a = 0,b = 0;        for(int i=0;i<nums.length;++i){           if(i%2==0){               a += nums[i];               a = Math.max(a,b);//偶数的dp           }else{               b += nums[i];   //上上dp+nums[i]               b = Math.max(a,b);//奇数的dp           }        }        return Math.max(a,b);           }}


Three:更简化

public class Solution {    public int rob(int[] nums) {        int a = 0,b = 0;        for(int i=0;i<nums.length;++i){            int m = a,n = b;//n为上上一个dp  m为上上上个dp+num[i-1]            a = nums[i] + n; //上上dp+nums[i]            b = Math.max(n,m);//m上上上个dp+nums[i-1]和n上上dp的上dp        }        return Math.max(a,b);           }}


0 0