这里有n个房子在一列直线上,现在我们需要给房屋染色,分别有红色蓝色和绿色。每个房屋染不同的颜色费用也不同,你需要设计一种染色方案使得相邻的房屋颜色不同,并且费用最小。
费用通过一个nx3 的矩阵给出,比如cost[0][0]表示房屋0染红色的费用,cost[1][2]表示房屋1染绿色的费用。
注意事项:
所有费用都是正整数
样例:
costs = [[14,2,11],[11,14,5],[14,3,10]] return 10
房屋 0 蓝色, 房屋 1 绿色, 房屋 2 蓝色, 2 + 5 + 3 = 10
思路:
修改costs矩阵的值,对于每一行,
costs[i][j]=costs[i][j]+min(costs[i−1][(j+1)%3],costs[i−1][(j+2)%3])
求修改后矩最后一行的最小值,即为结果。
#ifndef C515_H
#define C515_H
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
/*
* @param costs: n x 3 cost matrix
* @return: An integer, the minimum cost to paint all houses
*/
int minCost(vector<vector<int>> &costs) {
// write your code here
if (costs.empty())
return 0;
int size = costs.size();
if (size == 1)
return minVal(costs[0][0],minVal(costs[0][1],costs[0][2]));
for (int i = 1; i < size; ++i)
{
for (int j = 0; j < 3; ++j)
{
costs[i][j] = costs[i][j] + minVal(costs[i - 1][(j + 1) % 3], costs[i - 1][(j + 2) % 3]);
}
}
return minVal(costs[size - 1][0], minVal(costs[size - 1][1], costs[size - 1][2]));
}
int minVal(int a,int b)
{
return a < b ? a : b;
}
};
#endif