lintcode 515. Paint House

Paint House

 

自己的写法:

class Solution {
public:
    /**
     * @param costs: n x 3 cost matrix
     * @return: An integer, the minimum cost to paint all houses
     */
    int minCost(vector<vector<int> > &costs) {
        // write your code here
        int length = costs.size();
        vector<vector<int> > dp(length + 1,vector<int>(3));
        for(int i = 0;i < 3;i++)
            dp[0][i] = 0;
        for(int i = 1;i <= length;i++){
            dp[i][0] = min(dp[i-1][1] + costs[i-1][0],dp[i-1][2] + costs[i-1][0]);
            dp[i][1] = min(dp[i-1][0] + costs[i-1][1],dp[i-1][2] + costs[i-1][1]);
            dp[i][2] = min(dp[i-1][0] + costs[i-1][2],dp[i-1][1] + costs[i-1][2]);
        }
        int min_num = INT_MAX;
        for(int i = 0;i < 3;i++){
            min_num = min(min_num,dp[length][i]);
        }
        return min_num;
    }
};

更优的写法:

https://www.cnblogs.com/grandyang/p/5319384.html

class Solution {
public:
    int minCost(vector<vector<int>>& costs) {
        if (costs.empty() || costs[0].empty()) return 0;
        vector<vector<int>> dp = costs;
        for (int i = 1; i < dp.size(); ++i) {
            dp[i][0] += min(dp[i - 1][1], dp[i - 1][2]);
            dp[i][1] += min(dp[i - 1][0], dp[i - 1][2]);
            dp[i][2] += min(dp[i - 1][0], dp[i - 1][1]);
        }
        return min(min(dp.back()[0], dp.back()[1]), dp.back()[2]);
    }
};

 

posted @ 2019-04-16 15:53  有梦就要去实现他  阅读(153)  评论(0编辑  收藏  举报