8.15 - hard - 48

265. Paint House II

一道dp的题目,主要是要找出状态和转移方程。但是怎么去找状态或者怎么去找转移方程还是很考验做题熟练度的,好像也没什么其他好的办法。

class Solution(object):
    def minCostII(self, costs):
        """
        :type costs: List[List[int]]
        :rtype: int
        """
        if not costs:
            return 0
        # dp[i][j] # paint 0 ~ ith house with the ending color j the minimum cost is dp[i][j]
        m = len(costs)
        n = len(costs[0])
        dp = [[sys.maxint for _ in range(n)] for _ in range(m)]
        for j in range(n):
            dp[0][j] = costs[0][j]
        
        for i in range(1, m):
            for j in range(n):
                for k in range(n):
                    if k != j:
                        dp[i][j] = min(dp[i][j], dp[i-1][k] + costs[i][j])
        res = sys.maxint
        for j in range(n):
            res = min(res, dp[m-1][j])
        
        return res
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容