198 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.

Example:

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. DP

实际耗时:0ms

public int rob(int[] nums) {
    if (nums == null || nums.length == 0) {
        return 0;
    }
    if (nums.length == 1) {
        return nums[0];
    }
    int[][] dp = new int[nums.length][2];
    //init
    dp[0][0] = 0;
    dp[0][1] = nums[0];
    for (int i = 1; i < nums.length; i++) {
        // if robber do not rob the house
        dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1]);
        // robber rob the house
        dp[i][1] = dp[i - 1][0] + nums[i];
    }
    return Math.max(dp[nums.length - 1][0], dp[nums.length - 1][1]);
}
踩过的坑:[]

  思路很简单,创建一个二维数组,dp[i][0]代表不抢第i个房间的,而dp[i][1]则代表抢这个房间,不停继续即可。做这种题目,包括类似递归的解法,一定要假设自己已经解出来了,然后再做,否则特别容易进入死胡同。

时间复杂度O(n)
空间复杂度O(n)

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容