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()); } };