6.House Robber(简单版抢银行)

Level:

  Easy

题目描述:

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个银行时,所能抢到的最多钱,那么状态转移方程很容易可以得出:dp[i]=max(dp[i-2]+num,dp[i-1]),其中num指的是第i个银行里钱的数目。

代码:

class Solution {
    public int rob(int[] nums) {
        if(nums.length==0||nums==null)
            return 0;
        int []dp=new int[nums.length+1];
        dp[0]=0;  //数组中前0个元素时抢到的最多钱
        dp[1]=nums[0];//数组中前1个元素时抢到的最多钱
        for(int i=2;i<=nums.length;i++){
            dp[i]=Math.max(dp[i-2]+nums[i-1],dp[i-1]);
        }
        return dp[nums.length];
    }
}
posted @ 2019-04-12 16:25  yjxyy  阅读(213)  评论(0编辑  收藏  举报