【问题标题】:LeetCode "Paint House" problem: time limit exceeded despite O(N) solution?LeetCode“油漆屋”问题:尽管 O(N) 解决方案超出了时间限制?
【发布时间】:2018-09-20 18:05:57
【问题描述】:

我正在尝试解决 LeetCode 上的 Paint House 问题。这是我尝试的解决方案:

import math


class Solution(object):
    def minCost(self, costs):
        """
        :type costs: List[List[int]]
        :rtype: int
        """
        if not costs:
            return 0
        if len(costs) == 1:
            return min(costs[0])
        return min(costs[0][color] + self.minCost(
            [exclude(costs[1], color), *costs[2:]])
            for color in range(3))


def exclude(arr, color):
    new_arr = arr.copy()
    new_arr[color] = math.inf
    return new_arr

基本上,在每所房子中,它都会考虑为该房子选择每种颜色并排除下一房子的选择的成本(通过将成本设置为无穷大)。我相信这应该是线性时间,因为递归调用是在到达 costs 数组的末尾之前进行的。

我错了吗?解决方案是否具有正确的时间复杂度,但运行速度比 LeetCode 施加的时间限制慢一点?

【问题讨论】:

  • 什么是油漆房问题?您提供了一个需要登录到另一个站点的链接。这不符合描述。

标签: python algorithm dynamic-programming


【解决方案1】:

我刚刚意识到,每次调用 minCost 不满足基本情况都会生成 三个 递归调用,因此调用次数呈指数增长。所以这不是线性时间解,超过时间限制是对的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-24
    • 1970-01-01
    • 1970-01-01
    • 2020-06-13
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    相关资源
    最近更新 更多