栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

数据结构与算法之LeetCode-剑指 Offer II 091. 粉刷房子-动态规划-DP

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

数据结构与算法之LeetCode-剑指 Offer II 091. 粉刷房子-动态规划-DP

剑指 Offer II 091. 粉刷房子 - 力扣(LeetCode)

DP 动态规划
  • 建立状态转移方程 dp[i][j]表示粉刷 从0到i号房子,且第i号房子被粉刷成第j种颜色时到最小成本 0<=i
  • 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
  • dp[i][j] = Math.min(dp[i-1][(j+1)mod(3)],dp[i-1][(j+2)mod3])+costs[i][j]
  • 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
        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)

    粉刷房子 - 粉刷房子 - 力扣(LeetCode)

    【宫水三叶】简单状态机 DP 运用题 - 粉刷房子 - 力扣(LeetCode)

    [Python/Java/TypeScript/Go] 动态规划 - 粉刷房子 - 力扣(LeetCode)

    转载请注明:文章转载自 www.mshxw.com
    本文地址:https://www.mshxw.com/it/990184.html
    我们一直用心在做
    关于我们 文章归档 网站地图 联系我们

    版权所有 (c)2021-2022 MSHXW.COM

    ICP备案号:晋ICP备2021003244-6号