Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

A typical DP

class Solution {
public:
    int minCost(vector<vector<int>>& costs) {
        size_t len = costs.size();
        if(len == 0) return 0;
        
        vector<vector<int>> dp(len, vector<int>(3, 0));
        dp[0] = costs[0];
        for(int i = 1; i < len; i ++)
        {
            for(int c = 0; c < 3; c ++)
            {
                unordered_set<int> cand = {0, 1, 2};
                cand.erase(c);
                auto it = cand.begin();
                int a = *it ++, b = *it;
                
                dp[i][c] = costs[i][c] + std::min(dp[i - 1][a], dp[i - 1][b]);
            }
        }
        return *std::min_element(dp[len - 1].begin(), dp[len - 1].end());
    }
};
posted on 2015-08-22 00:46  Tonix  阅读(174)  评论(0编辑  收藏  举报