题目描述:
There are a row of n houses, each house can be painted with one of the k colors. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color.
The cost of painting each house with a certain color is represented by a n x k cost matrix. For example, costs[0][0] is the cost of painting house 0 with color 0; costs[1][2] is the cost of painting house 1 with color 2, and so on... Find the minimum cost to paint all houses.
Note:
All costs are positive integers.
Example:
Input: [[1,5,3],[2,9,4]]
Output: 5
Explanation: Paint house 0 into color 0, paint house 1 into color 2. Minimum cost: 1 + 4 = 5;
Or paint house 0 into color 2, paint house 1 into color 0. Minimum cost: 3 + 2 = 5.
Follow up:
Could you solve it in O(nk) runtime?
class Solution {
public:
int minCostII(vector<vector<int>>& costs) {
if(costs.size()==0||costs[0].size()==0) return 0;
int min1=0, min2=0; // 记录之前的最小的两个花费
int pre_color=-1; // 记录之前最小花费的颜色
for(auto cost:costs)
{ // 需要三个临时变量记录当前的最小的两个花费和当前最小花费的颜色,因为在遍历的时候需要保证三个全局变量不变
int cur_min1=INT_MAX, cur_min2=INT_MAX, cur_color=-1;
for(int i=0;i<cost.size();i++)
{ // 遍历当前所有颜色,如果颜色和之前相同,则选择加上第二小的花费,否则加上最小花费
int min_cost=0;
if(i==pre_color) min_cost=min2+cost[i];
else min_cost=min1+cost[i];
if(min_cost<cur_min1)
{
cur_min2=cur_min1;
cur_min1=min_cost;
cur_color=i;
}
else if(min_cost>=cur_min1&&min_cost<cur_min2) cur_min2=min_cost;
}
min1=cur_min1, min2=cur_min2; pre_color=cur_color;
}
return min1;
}
};
本文介绍了一种解决房屋涂色问题的算法,目标是在确保相邻房屋颜色不同的前提下,找到最低的涂色总成本。通过动态规划的方法,记录每一步的最小成本及次小成本,最终得出整体的最小成本。
344

被折叠的 条评论
为什么被折叠?



