1. 程式人生 > >leetcode256- Paint House- medium

leetcode256- Paint House- medium

leetcode ted matrix general 定義 diff 就是 row nco

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.

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.

Note:
All costs are positive integers.

DP。數組定義是:dp[i][j]表示刷到第i+1房子用顏色j的最小花費

遞推公式是:dp[i][j] = dp[i][j] + min(dp[i - 1][(j + 1) % 3], dp[i - 1][(j + 2) % 3]); 也就是每一個房子 i 刷 j 顏色的最小花費是,當前刷的花費 + 前一個房子刷其他顏色的花費裏面最小的

返回值是:dp最後一行所有列裏的最小值。

class Solution {
    public int minCost(int[][] costs) {
        
        // corner case
        if (costs == null || costs.length == 0 || costs[0].length == 0) {
            return 0;
        }
        
        // general case
        int[][] dp = new int[costs.length][costs[0].length];
        
for (int j = 0; j < costs[0].length; j++) { dp[0][j] = costs[0][j]; } for (int i = 1; i < costs.length; i++) { for (int j = 0; j < costs[0].length; j++) { dp[i][j] = costs[i][j] + Math.min(dp[i - 1][(j + 1) % 3], dp[i - 1][(j + 2) % 3]); } } return Math.min(dp[dp.length - 1][0], Math.min(dp[dp.length - 1][1], dp[dp.length - 1][2])); } }

leetcode256- Paint House- medium