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

遞歸:

public class Solution {
    //result[i]表示搶到第i個店獲得的最大價值
    public static int[] result;

    //返回搶到的價值
    public int search(int idx, int[] nums) {
        if (idx < 0) {
            return 0;
        }

        //此處要大於等於0
        if(result[idx] >= 0) {
            return result[idx];
        }
        /*
        idx不偷:idx-1,idx-2,idx-3..........
        idx偷:  idx-2,idx-3,idx-4..........
        所以上面有重複計算
        */
        result[idx] = Math.max(search(idx - 1, nums), search(idx - 2, nums) + nums[idx]);
        return result[idx];
    }

    public int rob(int[] nums) {
        result = new int[nums.length];
        for(int i = 0; i < nums.length; i++) {
            result[i] = -1;
        }
        return search(nums.length-1, nums);
    }
}

遞推

public class Solution {
    //result[i]表示搶到第i個店獲得的最大價值
    public static int[] result;

    public int rob(int[] nums) {

        if(nums.length == 0) {
            return 0; 
        }
        if(nums.length == 1) {
            return nums[0];
        }

        result = new int[nums.length];
        for(int i = 0; i < nums.length; i++) {
            result[i] = 0;
        }

        result[0] = nums[0];
        result[1] = Math.max(nums[0], nums[1]);

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

        return result[nums.length-1];
    }
}

關於動態規劃

動態規劃 (Dynamic Programming)
最優子結構
子問題最優決策可導出原問題最優決策
無後效性(就是讓問題縮小後跟原問題是一個問題就行)
重疊子問題
去冗餘
空間換時間(注意分析時空複雜度)

DP可以解決的問題如下:
最優,最大,最小,最長,計數

DP的解題步驟:

  • 設計暴力算法,找到冗餘
  • 設計並存儲狀態(一維,二維,三維數組,甚至用Map)
  • 遞歸式(狀態轉移方程)
  • 自底向上計算最優解(編程方式)

自底向上:從0(頭)開始解決問題,遞推實現
自頂向下:從n(末尾)開始解決問題,遞歸實現

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章