码迷,mamicode.com
首页 > 其他好文 > 详细

256. Paint House

时间:2016-08-11 08:35:07      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:

1. 把整个图色看成是一棵树,然后dfs

根节点有三个分叉:r,g,b

第二层(g,b),(r,b),(r,g)

所以就是相当于path sum

 1     int min = Integer.MAX_VALUE;
 2     
 3     public int minCost(int[][] costs) {
 4         if(costs.length == 0 || costs[0].length == 0) {
 5             return 0;
 6         }
 7         for(int i = 0; i < 3; i++) {
 8             sum(costs, 0, 0, i);
 9         }
10         return min;
11     }
12     
13     private void sum(int[][] costs, int houseNo, int lastSum, int curColor) {
14         if(houseNo == costs.length - 1) {
15             min = Math.min(min, lastSum + costs[houseNo][curColor]);
16             return;
17         }
18         List<Integer> list = new ArrayList<Integer>(Arrays.asList(0,1,2));
19         list.remove(curColor);
20         for(int i: list) {
21             sum(costs, houseNo + 1, lastSum + costs[houseNo][curColor], i);
22         }
23     }

时间复杂度应该是O(2^n)

哈哈然后LTE了

2. 动规

既然递归会超时,那就动规了

 1     public int minCost(int[][] costs) {
 2         int len = costs.length;
 3         if(len == 0 || costs.length == 0) {
 4             return 0;
 5         }
 6         int[][] path = new int[len][3];
 7         int min = Integer.MIN_VALUE;
 8         for(int i = 0; i < 3; i++) {
 9             path[0][i] = costs[0][i];
10         }
11         for(int i = 1; i < len; i++) {
12             path[i][0] = Math.min(path[i-1][1], path[i-1][2]) + costs[i][0];
13             path[i][1] = Math.min(path[i-1][0], path[i-1][2]) + costs[i][1];
14             path[i][2] = Math.min(path[i-1][0], path[i-1][1]) + costs[i][2];
15         }
16         return Math.min(path[len-1][0], Math.min(path[len-1][1], path[len-1][2]));
17     }

这样只有O(N)了

256. Paint House

标签:

原文地址:http://www.cnblogs.com/warmland/p/5759538.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!