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)

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容