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)