当前位置:网站首页>【剑指 Offer II 091. 粉刷房子】
【剑指 Offer II 091. 粉刷房子】
2022-06-25 16:22:00 【Sugar_wolf】
来源:力扣(LeetCode)
描述:
假如有一排房子,共 n 个,每个房子可以被粉刷成红色、蓝色或者绿色这三种颜色中的一种,你需要粉刷所有的房子并且使其相邻的两个房子颜色不能相同。
当然,因为市场上不同颜色油漆的价格不同,所以房子粉刷成不同颜色的花费成本也是不同的。每个房子粉刷成不同颜色的花费是以一个 n x 3 的正整数矩阵 costs 来表示的。
例如,costs[0][0] 表示第 0 号房子粉刷成红色的成本花费;costs[1][2] 表示第 1 号房子粉刷成绿色的花费,以此类推。
请计算出粉刷完所有房子最少的花费成本。
示例 1:
输入: costs = [[17,2,17],[16,16,5],[14,3,19]]
输出: 10
解释: 将 0 号房子粉刷成蓝色,1 号房子粉刷成绿色,2 号房子粉刷成蓝色。
最少花费: 2 + 5 + 3 = 10。
示例 2:
输入: costs = [[7,6,2]]
输出: 2
提示:
- costs.length == n
- costs[i].length == 3
- 1 <= n <= 100
- 1 <= costs[i][j] <= 20
方法 :动态规划


代码:
class Solution {
public:
int minCost(vector<vector<int>>& costs) {
int n = costs.size();
vector<int> dp(3);
for (int j = 0; j < 3; j++) {
dp[j] = costs[0][j];
}
for (int i = 1; i < n; i++) {
vector<int> dpNew(3);
for (int j = 0; j < 3; j++) {
dpNew[j] = min(dp[(j + 1) % 3], dp[(j + 2) % 3]) + costs[i][j];
}
dp = dpNew;
}
return *min_element(dp.begin(), dp.end());
}
};
执行用时:4 ms, 在所有 C++ 提交中击败了96.45%的用户
内存消耗:9.5 MB,在所有 C++ 提交中击败了56.50%的用户
author:LeetCode-Solution
边栏推荐
- Read mysql45 - a simple understanding of global locks and table locks
- 1-8Vmware中的文件共享
- Uniapp to preview pictures (single / multiple)
- GO语言-什么是临界资源安全问题?
- Coredata data persistence
- Reverse series to obtain any wechat applet code
- Navicat Premium 15 for Mac(数据库开发工具)中文版
- What can one line of code do?
- Catheon gaming appointed mark Aubrey, former Asia Pacific head of Activision Blizzard, as CEO
- 解析数仓lazyagg查询重写优化
猜你喜欢
随机推荐
Cocoapods installation in 2021
【精通高并发】深入理解C语言基础与汇编下的C语言
When inputting text in the shutter textfield, if the page is refreshed, the cursor position will change.
Day_ 18 hash table, generic
加密潮流:时尚向元宇宙的进阶
APIJSON简单使用
Div element
Multiple decorators decorate a function
Day_ eleven
The database records are read through the system time under the Android system, causing the problem of incomplete Reading Records!
About the use of Aidl, complex data transmission
What are some tricks that novice programmers don't know?
_ 17 collection overview
Bugly hot update usage
深入理解和把握数字经济的基本特征
User registration, information writing to file
卡尔曼时间序列预测
Catheon gaming appointed mark Aubrey, former Asia Pacific head of Activision Blizzard, as CEO
Optimization of lazyagg query rewriting in parsing data warehouse
Generate post order traversal according to pre order traversal and mid order traversal










