zoukankan      html  css  js  c++  java
  • 265. Paint House II


    /* * 265. Paint House II * 2016-6-24 by Mingyang * 这个题目说简单也简单,说难也难,因为简单在于他可以用n^3很容易做出来,这样的话就不用担心 * 但是要用平方做出来非常复杂 * 第一种跟I一样: * Define dp[n][k], where dp[i][j] means for house i with color j the minimum cost. * Initial value: dp[0][j] = costs[0][j]. For others, dp[i][j] = Integer.MAX_VALUE;, i >= 1 * Transit function: dp[i][j] = Math.min(dp[i][j], dp[i - 1][k] + cost[i][j]), where k != j. * Final state: Min(dp[n - 1][k]). */ public int minCostII(int[][] costs) { if (costs == null || costs.length == 0) { return 0; } int n = costs.length; int k = costs[0].length; // dp[i][j] means the min cost painting for house i, with color j int[][] dp = new int[n][k]; // Initialization for (int i = 0; i < k; i++) { dp[0][i] = costs[0][i]; } for (int i = 1; i < n; i++) { for (int j = 0; j < k; j++) { dp[i][j] = Integer.MAX_VALUE; for (int m = 0; m < k; m++) { if (m != j) { dp[i][j] = Math.min(dp[i - 1][m] + costs[i][j], dp[i][j]); } } } } // Final state int minCost = Integer.MAX_VALUE; for (int i = 0; i < k; i++) { minCost = Math.min(minCost, dp[n - 1][i]); } return minCost; } //这就是高手的平方做法,就是用两个index分别来存这一行里面,最小的和第二小的颜色的值,然后不断地更新 public int minCostII2(int[][] costs) { if (costs == null || costs.length == 0) return 0; int n = costs.length, k = costs[0].length; // min1 is the index of the 1st-smallest cost till previous house // min2 is the index of the 2nd-smallest cost till previous house int min1 = -1, min2 = -1; for (int i = 0; i < n; i++) { int last1 = min1, last2 = min2; min1 = -1; min2 = -1; for (int j = 0; j < k; j++) { if (j != last1) { // current color j is different to last min1 costs[i][j] += last1 < 0 ? 0 : costs[i - 1][last1]; } else { costs[i][j] += last2 < 0 ? 0 : costs[i - 1][last2]; } // find the indices of 1st and 2nd smallest cost of painting current house i if (min1 < 0 || costs[i][j] < costs[i][min1]) { min2 = min1; min1 = j; } else if (min2 < 0 || costs[i][j] < costs[i][min2]) { min2 = j; } } } return costs[n - 1][min1]; }
  • 相关阅读:
    [转]我们都是花栗鼠
    学习Tkinter
    彻底理解Python切片
    信息隐藏技术
    Hex棋
    web服务器一些概念
    Redis学习笔记
    Python知识总结(二)
    Python知识总结
    最小联结词组
  • 原文地址:https://www.cnblogs.com/zmyvszk/p/5615811.html
Copyright © 2011-2022 走看看