[LeetCode] 256. Paint House 粉刷房子

2021年09月15日 阅读数:1
这篇文章主要向大家介绍[LeetCode] 256. Paint House 粉刷房子,主要内容包括基础应用、实用技巧、原理机制等方面,希望对大家有所帮助。

There are a row of n houses, each house can be painted with one of the three colors: red, blue or green. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color.java

The cost of painting each house with a certain color is represented by a n x 3 cost matrix. For example, costs[0][0] is the cost of painting house 0 with color red; costs[1][2] is the cost of painting house 1 with color green, and so on... Find the minimum cost to paint all houses.数组

example:blog

Given costs = [[14,2,11],[11,14,5],[14,3,10]] return 10three

house 0 is blue, house 1 is green, house 2 is blue, 2 + 5 + 3 = 10it

Note:
All costs are positive integers.io

 

解题思路:class

房子i的最小涂色开销是房子i-1的最小涂色开销,加上房子i自己的涂色开销。可是房子i的涂色方式须要根据房子i-1的涂色方式来肯定,因此咱们对房子i-1要记录涂三种颜色分别不一样的开销,这样房子i在涂色的时候,咱们就知道三种颜色各自的最小开销是多少了。咱们在原数组上修改,能够作到不用空间。im

State: dp[i][j] // three colors: j = 0 or 1 or 2, static

Function: di

    dp[i][0] = dp[i][0] + min(dp[i - 1][1], dp[i -1][2])

    dp[i][1] = dp[i][1] + min(dp[i - 1][0], dp[i - 1][2])

    dp[i][2] = dp[i][2] + min(dp[i - 1][0], dp[i - 1][1])    

Initialize: dp = costs

Return: min(dp[n][0], dp[n][1], dp[n][2])

java 1: Time: O(n), Space: O(n)

public class Solution {
    public int minCost(int[][] costs) {
        int len = costs.length;
        if(costs != null && len == 0) return 0;
        int[][] dp = costs;
        for(int i = 1; i < len; i++){
            dp[i][0] = costs[i][0] + Math.min(costs[i - 1][1], costs[i - 1][2]);
            dp[i][1] = costs[i][1] + Math.min(costs[i - 1][0], costs[i - 1][2]);
            dp[i][2] = costs[i][2] + Math.min(costs[i - 1][0], costs[i - 1][1]);
        }
        return Math.min(dp[len - 1][0], Math.min(dp[len - 1][1], dp[len - 1][2]));
    }
  
    public static void main(String args[]) {
        int[][] costs = new int[][]{{14,2,11},{11,14,5},{14,3,10}};
        Solution sol = new Solution();
        System.out.println(sol.minCost(costs));
    }
}

   

Java 2: Time: O(n), Space: O(1)

class Solution {
    public int minCost(int[][] costs) {
        if(costs != null && costs.length == 0) return 0;        
        // 直接用原数组
        for(int i = 1; i < costs.length; i++){
            // 涂第一种颜色的话,上一个房子就不能涂第一种颜色,这样咱们要在上一个房子的第二和第三个颜色的最小开销中找最小的那个加上
            costs[i][0] = costs[i][0] + Math.min(costs[i - 1][1], costs[i - 1][2]);
            // 涂第二或者第三种颜色同理
            costs[i][1] = costs[i][1] + Math.min(costs[i - 1][0], costs[i - 1][2]);
            costs[i][2] = costs[i][2] + Math.min(costs[i - 1][0], costs[i - 1][1]);
        }
        // 返回涂三种颜色中开销最小的那个
        return Math.min(costs[costs.length - 1][0], Math.min(costs[costs.length - 1][1], costs[costs.length - 1][2]));
    }
}