当前位置:网站首页>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])
边栏推荐
- resilience4j 重试源码分析以及重试指标采集
- 学习太极创客 — MQTT 第二章(七)ESP8266 MQTT 遗嘱应用
- Leetcode week 299
- Use of WC command
- rsync远程同步
- 2022 tea master (intermediate) examination simulated 100 questions and simulated examination
- List of domestic database directory
- 1. integrate servlets
- [graduation season · advanced technology Er] hard work can only pass, hard work can be excellent!
- 各种类型长
猜你喜欢

ref属性,props配置,mixin混入,插件,scoped样式

2022 welder (elementary) special operation certificate examination question bank and answers

学习太极创客 — MQTT 第二章(七)ESP8266 MQTT 遗嘱应用

Flatten of cnn-lstm

2022茶艺师(中级)考试模拟100题及模拟考试

Leetcode 36. Effective Sudoku (yes, once)

csdn涨薪技术-Selenium自动化测试全栈总结

SQL server2019 create a new SQL server authentication user name and log in
![[learning notes] Introduction to principal component analysis](/img/24/a760d1cd095a967ef258b623eb465c.png)
[learning notes] Introduction to principal component analysis
![[go language questions] go from 0 to entry 5: comprehensive review of map, conditional sentences and circular sentences](/img/7a/16b481753d7d57f50dc8787eec8a1a.png)
[go language questions] go from 0 to entry 5: comprehensive review of map, conditional sentences and circular sentences
随机推荐
2022焊工(初级)特种作业证考试题库及答案
算力时代怎么「算」?「算网融合」先发优势很重要!
CNN-LSTM的flatten
head、tail查看文件
rsync远程同步
Input and output character data
522. 最长特殊序列 II(贪心&双指针)
2022 P cylinder filling test exercises and online simulation test
Day88. qiniu cloud: upload house source pictures and user avatars
How to understand the fast iteration of cloud native database?
2022年P气瓶充装考试练习题及在线模拟考试
国产数据库名录一览
2022 t elevator repair test question bank simulation test platform operation
Comparisonchain file name sort
Xiaobai's e-commerce business is very important to choose the right mall system!
QSP读取标签配置错误问题
【Try to Hack】Cobalt Strike(一)
Lecture 30 linear algebra Lecture 4 linear equations
APISIX 助力中东社交软件,实现本地化部署
iterator中的next()为什么要强转?