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.
Basic Idea:
思路 1:Memorized Search (dfs with memo)!!! Got TLE !!!
Java Code:
classSolution{publicintminCost(int[][]costs){if(costs ==null||costs.length==0)return0;returndfs(costs,0,-1,0,newHashMap<String,Integer>());}privateintdfs(int[][]costs,intpos,intlastColor,intcurrCost,Map<String,Integer>memo){if(pos ==costs.length)return currCost;String key = pos +","+ lastColor +","+ currCost;if(memo.containsKey(key))returnmemo.get(key);int ret =Integer.MAX_VALUE;for(int i =0; i <3;++i){if(i == lastColor)continue; ret =Math.min(ret, dfs(costs, pos +1, i, currCost + costs[pos][i], memo));}memo.put(key, ret);return ret;}}
思路 2:DP 连记忆化搜索都搞不定TLE,就只有DP一条路可以走了,就索性按DP的路子想一想。
对于第 i 个房子,我们有三种选择,我们把所有房子的三种可能状态分别记为一个数组,即 red[], green[], blue[];