当前位置:网站首页>力扣每日一题 剑指 Offer II 091. 粉刷房子
力扣每日一题 剑指 Offer II 091. 粉刷房子
2022-07-27 05:21:00 【最后一只三脚兽】
一道简单的DP问题,但是数据给的太小了,感觉暴力都能做,虽然我没想过
状态转移:
当前涂某个颜色的最小价格是前面另外两个颜色较便宜的一个的价格加上当前颜色的价格
状态转移方程:
f[0][i] = Math.min(f[1][i-1], f[2][i-1]) + costs[i-1][0];
f[1][i] = Math.min(f[0][i-1], f[2][i-1]) + costs[i-1][1];
f[2][i] = Math.min(f[0][i-1], f[1][i-1]) + costs[i-1][2];
class Solution {
public int minCost(int[][] costs) {
int n = costs.length;
int[][] f = new int[3][n+10];
f[0][0] = f[1][0] = f[2][0] = 0;
for(int i = 1; i<=n; i++){
f[0][i] = Math.min(f[1][i-1], f[2][i-1]) + costs[i-1][0];
f[1][i] = Math.min(f[0][i-1], f[2][i-1]) + costs[i-1][1];
f[2][i] = Math.min(f[0][i-1], f[1][i-1]) + costs[i-1][2];
}
int min = Math.min(f[0][n],f[1][n]);
return Math.min(min,f[2][n]);
}
}
- 时间复杂度O(n)
- 空间复杂度O(n)//由于只需要前面的值,可使用动态数组使空间复杂度将为O(1)
动态数组优化
class Solution {
int[][] f = new int[3][2];
void swap(){
for(int i=0; i<3; i++){
int tmp = f[i][0];
f[i][0] = f[i][1];
f[i][1] = tmp;
}
}
public int minCost(int[][] costs) {
int n = costs.length;
f[0][0] = f[1][0] = f[2][0] = 0;
for(int i = 1; i<=n; i++){
f[0][1] = Math.min(f[1][0], f[2][0]) + costs[i-1][0];
f[1][1] = Math.min(f[0]0], f[2][0]) + costs[i-1][1];
f[2][1] = Math.min(f[0][0], f[1][0]) + costs[i-1][2];
swap();
}
int min = Math.min(f[0][0],f[1][0]);
return Math.min(min,f[2][0]);
}
}
- 时间复杂度O(n)
- 空间复杂度O(1)//但实际上,由于数据较少,这种做法效果还没有上面的好
边栏推荐
- Stm32-fsmc extended memory SRAM
- Gbase 8C - SQL reference 6 SQL syntax (14)
- 2022.6.10 STM32MP157串口时钟的学习
- AE 3D particle system plug-in: Trapcode particle
- 解决conda install 安装停止、中断问题
- 编程学习记录——第6课【函数】
- 【头歌】重生之数据科学导论——回归进阶
- 11. Gradient derivation of perceptron
- c语言-线性顺序表
- 李宏毅 2020 深度学习与人类语言处理 DLHLP-Coreference Resolution-p21
猜你喜欢

剪枝-量化-转onnx中文系列教程

WebODM win10安装教程(亲测)

发布 分辨率0.22m的建筑物分割数据库

李宏毅 2020 深度学习与人类语言处理 DLHLP-Conditional Generation by RNN and Attention-p22

What tools are needed to make video post effects?

浅记一下十大排序

导数、偏导数以及梯度

Cesium教程 (1) 界面介绍-3dtiles加载-更改鼠标操作设置

Multi task foundation of IOT operating system
![[first song] machine learning of rebirth - linear regression](/img/70/3efd9eacf88f55022eb52d096926f7.png)
[first song] machine learning of rebirth - linear regression
随机推荐
2022.6.10 STM32MP157串口时钟的学习
Greedy high performance neural network and AI chip application research and training
C语言--字符串操作函数与内存操作函数
Day 2. Depressive symptoms, post-traumatic stress symptoms and suicide risk among graduate students
物联网操作系统
[song] rebirth of me in py introductory training (7): function call
【12】理解电路:从电报机到门电路,我们如何做到“千里传信”?
arcgis style样式表文件转换成geoserver sld文件
Unittest套件与运行器
pytorch转onnx相关问题
Baiwen driving Daquan learning (II) I2C driving
安全帽反光衣检测识别数据集和yolov5模型
个人开发者申请代码签名证书的签发流程
力扣题解 动态规划(3)
PZK学C语言之数据类型,进制转换,输入输出,运算符,分支语句ifelse
【Unity URP】代码获取当前URP配置UniversalRendererData,并动态添加RendererFeature
面试常问Future、FutureTask和CompletableFuture
C语言-动态内存管理
AE 3D粒子系统插件:Trapcode Particular
Live Home 3D Pro室内家居设计工具

