LintCode: 房屋染色 II
阿新 • • 發佈:2019-01-01
先用樸素的動態規劃,狀態轉移方程
ans[i][j] = min(ans[i-1][j]+cost[i][k], ans[i][j])
89%時提示超時。
class Solution:
# @param {int[][]} costs n x k cost matrix
# @return {int} an integer, the minimum cost to paint all houses
def minCostII(self, costs):
# Write your code here
if not costs:
return 0
n = len(costs)
m = len(costs[0])
ans = [[9999999 for i in range(m)] for i in range(2)]
ans[0] = costs[0]
for i in range(1, n):
for j in range(m):
for k in range(m):
if j != k:
ans[1][j] = min(ans[0 ][k] + costs[i][j], ans[1][j])
ans[0] = ans[1]
ans[1] = [9999999 for i in range(m)]
return min(ans[0])