当前位置:网站首页>LeetCode每日一题——剑指 Offer II 091. 粉刷房子
LeetCode每日一题——剑指 Offer II 091. 粉刷房子
2022-06-28 20:25:00 【hyk今天写算法了吗】
题目
假如有一排房子,共 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
思路
典型的动态规划问题,可以将题中所给的costs数组作为dp数组,第一列、第二列、第三列意义分别是刷到本列墙所需要花费,状态转移方程即本列加上一行另外两列,最后返回dp数组最后一行的最小值即可。
题解
class Solution:
def minCost(self, costs: List[List[int]]) -> int:
n = len(costs) - 1
for i in range(1, len(costs)):
# 状态转移方程
costs[i][0] += min(costs[i-1][1],costs[i-1][2])
costs[i][1] += min(costs[i-1][0],costs[i-1][2])
costs[i][2] += min(costs[i-1][0],costs[i-1][1])
return min(costs[n])
边栏推荐
- Day88. qiniu cloud: upload house source pictures and user avatars
- Lucene构建索引的原理及源代码分析
- 管道 | 与重定向 >
- 软件watchdog和ANR触发memory dump讲解
- 各种类型长
- Please allow the "imperfection" of the current domestic Tob
- odoo15 Module operations are not possible at this time, please try again later or contact your syste
- 请允许当下国内ToB的「不完美」
- TcWind 模式设定
- Why does next() in iterator need to be forcibly converted?
猜你喜欢
How to recover after Oracle delete accidentally deletes table data

RT-Thread线程同步与线程通信

Learning Tai Chi Maker - mqtt Chapter II (VII) esp8266 mqtt Testament application

mysql-发生系统错误1067

方 差 分 析

阿里云 MSE 基于 Apache APISIX 的全链路灰度方案实践

2022 t elevator repair test question bank simulation test platform operation

学习太极创客 — MQTT 第二章(八)ESP8266 MQTT 用户密码认证

Day88. qiniu cloud: upload house source pictures and user avatars

Flatten of cnn-lstm
随机推荐
openGauss内核分析之查询重写
理解整个网络模型的构建
如何添加 logs来debug ANR 问题
03.hello_rust
数据标准化处理
数据资产为王,如何解析企业数字化转型与数据资产管理的关系?
Why does next() in iterator need to be forcibly converted?
Visualization of neural network structure in different frames
1. integrate servlets
输入分隔符
Jenkins pipeline's handling of job parameters
Win 10 create a gin framework project
市值1200亿美金,老牌财税巨头Intuit是如何做到的?
grep文本搜索工具
csdn涨薪技术-Selenium自动化测试全栈总结
28 rounds of interviews with 10 companies in two and a half years
Is it safe for CICC fortune to open an account? Let's talk about CICC fortune
Leetcode week 299
CNN-LSTM的flatten
risc-v指令集