LINTCODE——房屋染色II
思路:和房屋染色I一样,动态规划,不同的是,每一个房子的选择有K种,分析发现,令dp[i][j]表示为第i个房子染第j种颜色时的最小费用,则有等式dp[i][j] = costs[i-1][j]+min{dp[i-1][1toK且不等于j]}
class Solution {
public:
/*
* @param costs: n x k cost matrix
* @return: an integer, the minimum cost to paint all houses
*/
int minCostII(vector<vector<int>> &costs) {
// write your code here
if(costs.empty())
return 0;
int n = costs.size();
int k = costs[0].size();
vector<vector<int> > dp(n+1,vector<int>(k,0));
//建立两个pair存储每一列的最小值,和次小值
vector< pair<int,int> > mintemp(2,make_pair(0,0));
for(int i = 1 ; i <= n ; i++)
{
pair<int ,int> temp(INT_MAX,0),temp1(INT_MAX,0);
for(int j = 0 ; j < k ; j++)
{
if( j != mintemp[0].second)
dp[i][j] = costs[i-1][j] + mintemp[0].first;
else
dp[i][j] = costs[i-1][j] + mintemp[1].first;
if(dp[i][j] < temp.first )
{
temp1 = temp;
temp = make_pair(dp[i][j] , j);
}
else if(dp[i][j] < temp1.first)
temp1 = make_pair(dp[i][j] , j);
}
mintemp[0] = temp;
mintemp[1] = temp1;
}
return mintemp[0].first;
}
};