[198] House Robber

1. 題目描述

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.

你是一個非常專業的小偷,一條街上有一排房間,每個房間中有一些錢,如果偷盜相鄰的房間會報警,求得最佳偷盜方案下偷到的資金數量。

2. 解題思路

使用動態規劃的思路,當走到每個房子的時候都有兩種選擇方案,搶還有不搶。
不搶:最大結果爲走到前一個房子所獲得的資金的最大值。
搶:最大結果爲前一個房子不搶時的最大值加上當前房子的金錢數。

3. Code

// Code1:使用兩個數組保存之前的最優解
public class Solution {
    public int rob(int[] nums) {
        // 使用兩個數組記錄當前偷了和沒偷得最大值
        if(nums.length == 0) return 0;
        else if(nums.length == 1) return nums[0];
        int houseNum = nums.length;
        int[] rob = new int[houseNum];
        int[] unrob = new int[houseNum];
        // 對第一間房偷和不偷賦值
        rob[0] = nums[0];
        unrob[0] = 0;
        for(int i = 1; i < houseNum; ++i)
        {
            // 偷當前房子時的最大值爲前一個房子沒偷得最大值+當前屋子金錢值
            rob[i] = unrob[i-1] + nums[i];
            // 不偷當前屋子的最大值爲前一個房子偷或不偷中值比較大的一個
            unrob[i] = Math.max(rob[i-1], unrob[i-1]);
        }
        return Math.max(rob[houseNum-1], unrob[houseNum-1]);
    }
}
// Code2:對於Code1的優化,使用兩個變量保存前一個的最優解
public class Solution {
    public int rob(int[] nums) {
        // 使用兩個數組記錄當前偷了和沒偷得最大值
        if(nums.length == 0) return 0;
        else if(nums.length == 1) return nums[0];
        int tempRob = 0;
        int tempUnrob = 0;
        int rob = 0;
        int unrob = 0;
        // 對第一間房偷和不偷賦值
        tempRob = nums[0];
        tempUnrob = 0;
        for(int i = 1; i < nums.length; ++i)
        {
            // 只需要保存走到前一個房子偷或不偷所產生的最大值即可
            rob = tempUnrob + nums[i];
            unrob = Math.max(tempRob, tempUnrob);
            tempRob = rob;
            tempUnrob = unrob;
        }
        return Math.max(rob, unrob);
    }
}
發佈了79 篇原創文章 · 獲贊 58 · 訪問量 15萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章