Standard dynamic programming solution with constant space


  • 0
    T
    class Solution {
    public:
        int minCost(vector<vector<int>>& costs) {
            if(costs.empty()) return 0;
            int n=costs.size();
            vector<vector<int>> dp(2,vector<int>(3,0));
            dp[0][0]=costs[0][0];
            dp[0][1]=costs[0][1];
            dp[0][2]=costs[0][2];
            for(int i=1;i<n;++i){
                for(int j=0;j<costs[i].size();++j){
                    dp[i%2][j]=costs[i][j]+min(dp[(i-1)%2][(j+1)%3],dp[(i-1)%2][(j+2)%3]);
                }
            }
            
            int res=min(dp[(n-1)%2][0],dp[(n-1)%2][1]);
            res=min(res,dp[(n-1)%2][2]);
            return res;
            
        }
    };

Log in to reply
 

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