My C++ DP solution - easy to understand!!!


  • 0
    E
    class Solution {
    public:
        int minCostII(vector<vector<int>>& costs) {
            if(costs.size() == 0) {
                return 0;
            }
            int n = costs.size();
            int k = costs[0].size();
            vector<int> f(k, 0);
            int min1 = 0;
            int min2 = 0;
            for(int i = 0 ; i < n ; ++i) {
                int last_min1 = min1;
                int last_min2 = min2;
                min1 = INT_MAX;
                min2 = INT_MAX;
                for(int j = 0 ; j < k ; ++j) {
                    f[j] = (f[j] == last_min1 ? last_min2 : last_min1) + costs[i][j];
                    if(min1 <= f[j]) {
                        min2 = min(min2, f[j]);
                    }
                    else {
                        min2 = min1;
                        min1 = f[j];
                    }
                }
            }
            return min1;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.