lintcode - 房屋染色

 1 class Solution {
 2 public:
 3     /*
 4      * @param costs: n x 3 cost matrix
 5      * @return: An integer, the minimum cost to paint all houses
 6      */
 7      const int inf = 0x3f3f3f3f;
 8      vector<vector<int> > dp;
 9     int minCost(vector<vector<int>> &costs) {
10         // write your code here'
11         if(costs.size() == 0) return 0;
12         dp.resize(costs.size(), vector<int>(3,inf));
13         for(int i = 0; i < costs.size(); ++i){
14                 for(int j = 0; j < 3; ++j){
15                         if(i == 0){
16                                 dp[i][j] = costs[i][j];
17                         } else {
18                                 vector<int> tmp = color(j);
19                                 dp[i][j] = min(dp[i-1][tmp[0]], dp[i-1][tmp[1]]) + costs[i][j];
20                         }
21                 }
22         }
23         return min(dp[costs.size() - 1][0], min(dp[costs.size() - 1][1], dp[costs.size() - 1][2]));
24     }
25     vector<int> color(int x){
26         vector<int> y;
27         if(x == 0){
28                 y.push_back(1);
29                 y.push_back(2);
30                 return y;
31         } else if(x == 1){
32                 y.push_back(0);
33                 y.push_back(2);
34                 return y;
35         } else {
36                 y.push_back(1);
37                 y.push_back(0);
38                 return y;
39         }
40     }
41 };

 

posted @ 2017-09-24 10:06  GeniusYang  阅读(433)  评论(0编辑  收藏  举报