LeetCode #265. Paint House II

本文介绍了一种解决房屋涂色问题的算法,目标是在确保相邻房屋颜色不同的前提下,找到最低的涂色总成本。通过动态规划的方法,记录每一步的最小成本及次小成本,最终得出整体的最小成本。

题目描述:

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;
    }
};

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值