【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;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值