【LeetCode】198. 打家劫舍

在這裏插入圖片描述

也就是找出最大的元素和,條件是這些元素都不相鄰。
我的思路是,利用動態規劃的方法,狀態轉移方程爲:f(x)=max{f(x-2),f(x-3)} + money(x)
f(x)的意思是,以x位置爲最後一家的能搶的最多的錢。money(x)是序號爲x的這一家人的錢數。
public class Solution {
    public int rob(int[] nums) {
        if (nums.length == 0) return 0;
        if (nums.length == 1) return nums[0];
        if (nums.length == 2) return Math.max(nums[0], nums[1]);
        if (nums.length == 3) return Math.max(nums[1], nums[0] + nums[2]);

        int[] res = new int[nums.length];
        res[0] = nums[0];
        res[1] = nums[1];
        res[2] = nums[0] + nums[2];
        int max = Math.max(res[0], res[1]);
        max = Math.max(max, res[2]);
        for (int i = 3; i < nums.length; i++) {
            res[i] = Math.max(res[i - 2], res[i - 3]) + nums[i];
            max = Math.max(max, res[i]);
        }
        return max;
    }
}

其實類似,斐波那契數列,不需要那麼多空間來儲存。並且遞推公式可以改一下。f(i) = max{f(i-1), f(i-2)+money(i)} 這裏f(i)表示包括第i家,能夠得到的最多的錢。
public class Solution {
    public int rob(int[] nums) {
        if (nums.length == 0) return 0;
        if (nums.length == 1) return nums[0];
        int pre = nums[0];
        int cur = Math.max(nums[0], nums[1]);
        for (int i = 2; i < nums.length; i++) {
            int tmp = cur;
            cur = Math.max(cur, pre + nums[i]);
            pre = tmp;
        }
        return cur;
    }
}

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