我正在尝试解决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规定的时间限制慢一点?
答案 0 :(得分:1)
我刚刚意识到,对minCost
的每次调用都不满足基本情况,因此会生成三个递归调用,因此调用数量呈指数增长。因此,这不是线性时间解决方案,而超过时间限制是正确的。