Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Logic:
- dp array rows represents houses and 3 columns for red,blue and green colors.
- dp[i][j] will store the minimum cost by coloring ith house by jth color ie. j=0->red,j=1->blue,j=2->green
- coloring of first house with jth colors will be costs[0][j]
- so,if we color ith house with red,then minimum cost till ith house will be min of cost of previous house
- colored with blue and green because same color can't be in adjacent house and same goes for other colors also.
- finally,in last row,we will have minimum cost coloring last house with red,blue and green,return their minimum.
- */
- int Solution::solve(vector<vector<int> > &costs) {
- int n=costs.size();
- vector<vector<int> > dp(n, 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<costs.size();i++){
- dp[i][0]=min(dp[i-1][1],dp[i-1][2])+costs[i][0];
- dp[i][1]=min(dp[i-1][0],dp[i-1][2])+costs[i][1];
- dp[i][2]=min(dp[i-1][0],dp[i-1][1])+costs[i][2];
- }
- n--;
- return min(min(dp[n][0],dp[n][1]),dp[n][2]);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement