Leetcode House Robber 提交 vs 自定义测试用例

Leetcode House Robber submission vs custom testcase

我正在研究 198. House Robber LeetCode 问题:

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 systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.

Example 1:

Input: nums = [1,2,3,1]
Output: 4

Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.

Example 2:

Input: nums = [2,7,9,3,1]
Output: 12

Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
Total amount you can rob = 2 + 9 + 1 = 12.

我的代码

class Solution:
    def rob(self, nums, n=0, memo={}):
        if n in memo:
            return memo[n]
        
        if n == len(nums) - 1:
            return nums[n]
        if n > len(nums) - 1:
            return 0
        
        f = nums[n] + self.rob(nums, n + 2)
        s = nums[n + 1] + self.rob(nums, n + 3)
        
        memo[n] = max(f, s)

        return max(f, s)

当我点击提交按钮时输入失败:[2,7,9,3,1]。但是当我 运行 它作为自定义测试用例时它似乎工作:

问题出在 memo 参数上。

因为它被定义 (memo={}) 它永远不会在测试用例之间被重置,所以它会携带与当前测试用例无关的值。

与其他语言不同,参数的默认值仅在函数定义时计算,而不是执行

因此请务必将 memo 定义为函数内的局部变量,而不是参数。

您可以在 rob 中创建一个作为 嵌套 函数的递归函数,以便在递归期间访问 memo 的相同实例。

因此将您的代码更改为:

def rob(self, nums):
    memo = {}  # define here so it gets reset at every call
    
    def recur(n):  # recursive function with access to memo
        if n in memo:
            return memo[n]

        if n == len(nums) - 1:
            return nums[n]
        if n > len(nums) - 1:
            return 0

        f = nums[n] + recur(n + 2)
        s = nums[n + 1] + recur(n + 3)

        memo[n] = max(f, s)

        return max(f, s)
    
    return recur(0)