LeetCode 256. Paint House
原题链接在这里: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:
1 public class Solution { 2 public int minCost(int[][] costs) { 3 if(costs == null || costs.length == 0){ 4 return 0; 5 } 6 int len = costs.length; 7 int red = 0; //最后print red 时的总共最小cost 8 int blue = 0; 9 int green = 0; 10 for(int i = 0; i<len; i++){ 11 int preRed = red; 12 int preBlue = blue; 13 int preGreen = green; 14 red = costs[i][0] + Math.min(preBlue, preGreen); //当前house选择red, 之前只能在blue 和 green中选 15 blue = costs[i][1] + Math.min(preRed, preGreen); 16 green = costs[i][2] + Math.min(preRed, preBlue); 17 } 18 return Math.min(red, Math.min(blue, green)); 19 } 20 }