[LeetCode] Paint House
Problem Description:
There are a row of n houses, each house can be painted with one of the three colors: red, blue or green. 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 3
cost matrix. For example, costs[0][0]
is the cost of painting house 0 with color red;costs[1][2]
is the cost of painting house 1 with color green, and so on... Find the minimum cost to paint all houses.
Note:
All costs are positive integers.
An interesting DP problem. This link posts a nice solution which gives costs[i][j] a new meaning and modify it directly and so save the usage of additional spaces.
Well, personally I would like to keep costs
unmodified. I rewrite the code in C++, a little verbose than the one in the above link:-)
1 class Solution { 2 public: 3 int minCost(vector<vector<int>>& costs) { 4 if (costs.empty()) return 0; 5 int n = costs.size(), r = 0, g = 0, b = 0; 6 for (int i = 0; i < n; i++) { 7 int rr = r, bb = b, gg = g; 8 r = costs[i][0] + min(bb, gg); 9 b = costs[i][1] + min(rr, gg); 10 g = costs[i][2] + min(rr, bb); 11 } 12 return min(r, min(b, g)); 13 } 14 };
r
/b
/g
in the i
-th loop means the minimum costs to paint the i
-th house in red/blue/green respectively plus painting the previous houses. The time and space complexities are still ofO(n)
and O(1)
.
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 深入理解 Mybatis 分库分表执行原理
· 如何打造一个高并发系统?
· .NET Core GC压缩(compact_phase)底层原理浅谈
· 现代计算机视觉入门之:什么是图片特征编码
· .NET 9 new features-C#13新的锁类型和语义
· Sdcb Chats 技术博客:数据库 ID 选型的曲折之路 - 从 Guid 到自增 ID,再到
· 语音处理 开源项目 EchoSharp
· 《HelloGitHub》第 106 期
· Spring AI + Ollama 实现 deepseek-r1 的API服务和调用
· 使用 Dify + LLM 构建精确任务处理应用