剑指 Offer II 091. 粉刷房子 - 力扣(LeetCode)
DP 动态规划
- 建立状态转移方程 dp[i][j]表示粉刷 从0到i号房子,且第i号房子被粉刷成第j种颜色时到最小成本 0<=i<n, 0<=j<3
- dp[i][0] = Math.minI(dp[i-1][1],dp[i-1][2])+costs[i][0]
- dp[i][1] = Math.minI(dp[i-1][0],dp[i-1][2])+costs[i][1]
- dp[i][2] = Math.minI(dp[i-1][0],dp[i-1][1])+costs[i][2]
- 求得总的状态转移方程 (1<=i<n,0<=j<3)
- dp[i][j] = Math.min(dp[i-1][(j+1)mod(3)],dp[i-1][(j+2)mod3])+costs[i][j]
/**
* @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)