每日一题做题记录,参考官方和三叶的题解 |
class Solution {
public int minCost(int[][] costs) {
int r = costs[0][0], b = costs[0][1], g = costs[0][2];
for (int i = 1; i < costs.length; i++) {
int nr = Math.min(b, g) + costs[i][0];
int nb = Math.min(r, g) + costs[i][1];
int ng = Math.min(r, b) + costs[i][2];
r = nr;
b = nb;
g = ng;
}
return Math.min(r, Math.min(b, g));
}
}
class Solution {
public:
int minCost(vector<vector<int>>& costs) {
int r = costs[0][0], b = costs[0][1], g = costs[0][2];
for (int i = 1; i < costs.size(); i++) {
int nr = min(b, g) + costs[i][0];
int nb = min(r, g) + costs[i][1];
int ng = min(r, b) + costs[i][2];
r = nr;
b = nb;
g = ng;
}
return min(r, min(b, g));
}
};
impl Solution {
pub fn min_cost(costs: Vec<Vec<i32>>) -> i32 {
let (mut r, mut b, mut g) = (costs[0][0], costs[0][1], costs[0][2]);
for i in 1..costs.len() {
let nr = b.min(g) + costs[i][0];
let nb = r.min(g) + costs[i][1];
let ng = r.min(b) + costs[i][2];
r = nr;
b = nb;
g = ng;
}
r.min(b.min(g))
}
}
into_iter()
impl Solution {
pub fn min_cost(costs: Vec<Vec<i32>>) -> i32 {
*costs.into_iter().fold([0, 0, 0], |rbg, cur| [cur[0] + rbg[1].min(rbg[2]), cur[1] + rbg[0].min(rbg[2]), cur[2] + rbg[0].min(rbg[1])]).iter().min().unwrap()
}
}
常有的DP思维,下一栋房子的颜色只和上一栋有关就很ez。
欢迎指正与讨论! |