Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
paint-house-ii.py 1.30 KB
一键复制 编辑 原始数据 按行查看 历史
Allen Liu 提交于 2018-10-13 01:56 +08:00 . add complexity
# Time: O(n * k)
# Space: O(k)
class Solution2(object):
def minCostII(self, costs):
"""
:type costs: List[List[int]]
:rtype: int
"""
return min(reduce(self.combine, costs)) if costs else 0
def combine(self, tmp, house):
smallest, k, i = min(tmp), len(tmp), tmp.index(min(tmp))
tmp, tmp[i] = [smallest] * k, min(tmp[:i] + tmp[i+1:])
return map(sum, zip(tmp, house))
class Solution2(object):
def minCostII(self, costs):
"""
:type costs: List[List[int]]
:rtype: int
"""
if not costs:
return 0
n = len(costs)
k = len(costs[0])
min_cost = [costs[0], [0] * k]
for i in xrange(1, n):
smallest, second_smallest = float("inf"), float("inf")
for j in xrange(k):
if min_cost[(i - 1) % 2][j] < smallest:
smallest, second_smallest = min_cost[(i - 1) % 2][j], smallest
elif min_cost[(i - 1) % 2][j] < second_smallest:
second_smallest = min_cost[(i - 1) % 2][j]
for j in xrange(k):
min_j = smallest if min_cost[(i - 1) % 2][j] != smallest else second_smallest
min_cost[i % 2][j] = costs[i][j] + min_j
return min(min_cost[(n - 1) % 2])
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助