Problem #19 [Medium]

This problem was asked by Facebook.

A builder is looking to build a row of N houses that can be of K different colors. He has a goal of minimizing cost while ensuring that no two neighboring houses are of the same color.

Given an N by K matrix where the nth row and kth column represents the cost to build the nth house with kth color, return the minimum cost which achieves this goal.
暴力解法是把所有房子满足染色要求的选择列出来,然后选个成本最小的。

import itertools

def min_cost_to_paint_houses(N, K, cost):
    # Generate all possible combinations of colors for N houses
    all_color_combinations = itertools.product(range(K), repeat=N)
    
    min_cost = float('inf')
    # Iterate through all combinations and calculate total cost
    for colors in all_color_combinations:
        total_cost = 0
        valid = True
        for i in range(N):
            if i>=1 and colors[i] == colors[i - 1]: 
                valid = False
                break
            total_cost += cost[i][colors[i]]
        if valid:
            min_cost = min(min_cost, total_cost) 

    return min_cost

# Example usage:
N = 3
K = 3  # Assuming 4 colors
cost = [[14,2,11],
        [11,14,5],
        [14,3,10]]

print("Minimum cost:", min_cost_to_paint_houses(N, K, cost))

上述方法时间复杂度为O(KN),额外空间为all_color_combination生成元组的数量乘以每个元组的长度,因此空间复杂度为O(N*KN)
其实本题和Problem #9很像,可以自行搜索前文。9中我们只有选和不选两种选择,现在是K种选择。

import itertools

def min_cost_to_paint_houses(cost):
    N = len(cost)
    K = len(cost[0])
    if N == 0:
       return 0
    dp = [[0] * K for _ in range(N)]
    for i in range(K):
        dp[0][i] = cost[0][i]

    for i in range(1,N):
        for j in range(K):
            min_dp = float('inf')
            for z in range(K):
                if z != j:
                    min_dp = min(min_dp, dp[i-1][z])
            dp[i][j] = min_dp + cost[i][j]

    min_dp = float('inf')
    for i in range(K):
        min_dp = min(min_dp, dp[N-1][i])
    return min_dp
    
# Example usage:
cost = [[14,2,11],
        [11,14,5],
        [14,3,10]]

print("Minimum cost:", min_cost_to_paint_houses(cost))

时间复杂度为O(N*K2)
空间复杂度就是dp数组O(NK)

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值