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]
超时了!

你可能感兴趣的:(LeetCode)