House Robber--lintcode

Description

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

Given [3, 8, 4], return 8.

分析:这题是动态规划 找公式 规律题。

思路过程:开始的时候我想用的是二维数组 和两个for循环。这个是动态规划题的常见套路。可是在模拟二维数组的时候,发现数组A只能作为一个轴,不能同时作为x轴和y轴。所以这个方法不行。 之后又想了一下,发现偷了一家之后 要偷下下家,或下下家才行。这个有点像 爬楼梯 只能走一个台阶或两个台阶。
所以我就朝爬楼梯方向模拟。最后终于模拟成功。

主要思路是 以A,B,C,D四家为例。在偷D家时,必须是从A家过来或B家过来。然后选取A,B家中钱最多的一个 赋值给temp数组。temp数组是记录偷到某家时,已经偷到的钱数。

public long houseRobber(int[] A) {
        // write your code here
        if(A.length==0) return 0;
        if(A.length==1) return A[0];
         if(A.length==2) return (A[0]>A[1]?A[0]:A[1]);
        long[] temp=new long[A.length];
        temp[0]=A[0];
         temp[1]=A[1];
        temp[2]=A[0]+A[2];
        for(int i=3;i<A.length;i++){
           temp[i]=(temp[i-2]>temp[i-3]?temp[i-2]:temp[i-3])+A[i];
        }
        return (temp[A.length-1]>temp[A.length-2]?temp[A.length-1]:temp[A.length-2]);

    }

但是网上搜了一下 还有一种思路:
一条直线上有n座房子,每座房子里都有一定的现金(用nums[i]表示),不能同时抢劫相邻的两座房子,问最多能抢劫多少钱?这是一道典型的动态规划,用money[i]表示从第1座房子到第i座房子能抢到的最多的钱,那么money[i] = max(money[i - 2] + nums[i], money[i - 1])。

 public int rob1(int[] num) {  
        if (num.length == 0) return 0;  

        int[] dp = new int[num.length + 1];  
        dp[0] = 0;  
        dp[1] = num[0];  

        for (int i = 2; i <= num.length; i++) {  
            dp[i] = Math.max(dp[i - 1], dp[i - 2] + num[i - 1]);  
        }  

        return dp[num.length];  
    }  

参考网址:http://blog.csdn.net/ljiabin/article/details/46958233

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值