leetcode 198.House Robber-打家劫舍|动态规划

原题链接:198.House Robber

【思路-Java、Python】递归实现

考查动态规划,基本思路是当前节点处最大值curMax = Math.max(curMax, curPrePreMax + cur)。举个例子[3, 2, 4, 7, 5, 6]

3     |                2                |            4           |         7            5           6

       |   curPrePreMax:3   |  curMax:7     |    cur:7

那么经过上述公式计算,curMax = 10:

    public int rob(int[] nums) {
        int curMax = 0, curPrePreMax = 0;
        for (int cur : nums) {
            int temp = curMax;
            curMax = Math.max(curMax, curPrePreMax + cur);
            curPrePreMax = temp;
        }
        return curMax;
    }
69 / 69  test cases passed. Runtime: 0 ms   Your runtime beats 48.10% of javasubmissions.

class Solution(object):
    def rob(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        arr=[0]*2
        for num in nums :
            arr[0] = max(arr[0]+num, arr[1])
            arr[0], arr[1] = arr[1], arr[0]
        return arr[1]
69 / 69  test cases passed. Runtime: 52 ms  Your runtime beats 27.92% of pythonsubmissions.

【补充】非递归实现
提供一种新思路,当作参考吧!
public class Solution {
    public int rob(int[] nums) {
        return dp(nums, nums.length-1);
    }
    private int dp(int[] nums, int i) {
        if(i == -1) return 0;
        if(i == 0) return nums[0];
        return Math.max(dp(nums, i-1), dp(nums, i-2)+nums[i]);
    }
}
Submission Result: Time Limit Exceeded 
Last executed input:[104,209,137,52,158,67,213,86,141,110,151,127,238,147,169,138,240,185,246,225,147,203,83,83,131,227,54,78,165,180,214,151,111,161,233,147,124,143]
超时了!
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值