LINTCODE——房屋染色II

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;

    }


};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值