• 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]);
        }
    };
  • 相关阅读:
    枚举和字符串转换
    JavaScript string.format
    Jquery 中toggle的用法举例
    JQuery 实现倒计时
    找位置
    图算法
    文件操作总结
    动态规划——总结
    回文字符串
    a+b_1
  • 原文地址:https://www.cnblogs.com/ymjyqsx/p/10717706.html
Copyright © 2020-2023  润新知