Leetcode 256. Paint House
题目

解法1:brutal force
暴力解法就是产生所有组合,选取最小的。时间复杂度会是3的n次
解法2:recursion
使用recursion其实是bottom-up的解法。在这边会超时,但是这里的recursion其实已经解释了动态规划应该怎么做
class Solution:
def minCost(self, costs: List[List[int]]) -> int:
def paint_cost(n,color):
total_costs = costs[n][color]
if n==len(costs)-1:
return total_costs
if color==0:
total_costs += min(paint_cost(n+1,1),paint_cost(n+1,2))
elif color==1:
total_costs += min(paint_cost(n+1,0),paint_cost(n+1,2))
else:
total_costs += min(paint_cost(n+1,0),paint_cost(n+1,1))
return total_costs
if not costs:
return 0
return min(paint_cost(0,0),paint_cost(0,1

这篇博客介绍了LeetCode 256题——Paint House的四种解法,包括暴力求解、递归、记忆化搜索和自底向上动态规划。重点讨论了如何通过记忆化搜索和动态规划降低时间复杂度,从3的n次方到3*n,以及CPP实现动态规划的建议链接。
最低0.47元/天 解锁文章
1905

被折叠的 条评论
为什么被折叠?



