LeetCode Paint House

时间:2022-07-07 21:43:37

原题链接在这里:https://leetcode.com/problems/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.

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.

题解:

DP问题. 类似House Robber. red = 当前房子paint red cost + Math.min(之前paint blue的总花费,之前paint green的总花费). blue 和 gree 同理.

Time Complexity: O(n). Space: O(1).

AC Java:

 public class Solution {
public int minCost(int[][] costs) {
if(costs == null || costs.length == 0){
return 0;
}
int len = costs.length;
int red = 0; //最后print red 时的总共最小cost
int blue = 0;
int green = 0;
for(int i = 0; i<len; i++){
int preRed = red;
int preBlue = blue;
int preGreen = green;
red = costs[i][0] + Math.min(preBlue, preGreen); //当前house选择red, 之前只能在blue 和 green中选
blue = costs[i][1] + Math.min(preRed, preGreen);
green = costs[i][2] + Math.min(preRed, preBlue);
}
return Math.min(red, Math.min(blue, green));
}
}

跟上Paint House IIPaint Fence.