剑指 Offer II 091. 粉刷房子 - 力扣(LeetCode)
/**
* @param {number[][]} costs
* @return {number}
*/
var minCost = function(costs) {
const n = costs.length;
let dp = new Array(3).fill(0);
for(let j=0;j<3;j++){
dp[j] = costs[0][j];
}
for(let i=1;i<n;i++){
const dpNew = new Array(3).fill(0);
for(let j=0;j<3;j++){
dpNew[j] = Math.min(dp[(j+1)%3],dp[(j+2)%3]) + costs[i][j];
}
dp = dpNew;
}
return parseInt(Math.min(...dp));
};
class Solution {
public int minCost(int[][] cs) {
int n = cs.length;
int a = cs[0][0], b = cs[0][1], c = cs[0][2];
for (int i = 1; i < n; i++) {
int d = Math.min(b, c) + cs[i][0];
int e = Math.min(a, c) + cs[i][1];
int f = Math.min(a, b) + cs[i][2];
a = d; b = e; c = f;
}
return Math.min(a, Math.min(b, c));
}
}
function minCost(costs: number[][]): number {
let red = 0, blue = 0, green = 0
for (const [r, b, g] of costs) {
[red, blue, green] = [Math.min(blue, green) + r, Math.min(red, green) + b, Math.min(red, blue) + g]
}
return Math.min(red, blue, green)
};
var minCost = function(costs){
let red = 0, green = 0, blue = 0;
for(const [r,g,b] of costs){
[red,green,blue] = [Math.min(blue,green)+r,Math.min(red,blue)+g,Math.min(red,green)+b]
}
return Math.min(red,green,blue)
}
执行结果:通过
执行用时:68 ms, 在所有 JavaScript 提交中击败了57.35%的用户
内存消耗:43.7 MB, 在所有 JavaScript 提交中击败了34.60%的用户
通过测试用例:100 / 100
剑指 Offer II 091. 粉刷房子 - 力扣(LeetCode)