Paint House
There is a row of n houses, each house can is painted with one of the three colors:red, blue or green. The cost of painting a certain color is different. You had to paint all the houses such, that no, and adjacent houses have the same color.
The cost of painting a certain color was represented by a cost n x 3
matrix. For example, was the cost of costs[0][0]
painting House 0 with color red; costs[1][2]
the cost of Painting House 1 with color green, And so on ... Find the minimum cost-to-paint all houses.
Note:
All costs is positive integers.
1 classSolution {2 Public:3 intMincost (vector<vector<int>>&costs) {4 if(Costs.empty ())return 0;5 for(inti =1; I < costs.size (); ++i) {6 for(intj =0; J <3; ++j) {7COSTS[I][J] + = min (costs[i-1[(j+1)%3], costs[i-1[(j+2)%3]);8 }9 }Ten returnMin (Costs.back () [0], Min (Costs.back () [1], Costs.back () [2])); One } A};
Paint House II
There is a row of n houses, each house can is painted with one of the K colors. The cost of painting a certain color is different. You had to paint all the houses such, that no, and adjacent houses have the same color.
The cost of painting a certain color was represented by a cost n x k
matrix. For example, was the cost of costs[0][0]
painting House 0 with color 0; costs[1][2]
is the cost of Painting House 1 with color 2, ... Find the minimum cost-to-paint all houses.
Note:
All costs is positive integers.
Follow up:
Could you solve it in O(nk) runtime?
1 classSolution {2 Public:3 intMincostii (vector<vector<int>>&costs) {4 if(Costs.empty () | | costs[0].empty ())return 0;5 intn = costs.size (), k = costs[0].size ();6vector<int>Min1 (k), min2 (k);7 for(inti =1; I < costs.size (); ++i) {8min1[0] =Int_max;9 for(intj =1; J < K; ++j) {TenMin1[j] = min (min1[j-1], costs[i-1][j-1]); One } Amin2[k-1] =Int_max; - for(intj = k-2; J >=0; --j) { -Min2[j] = min (min2[j+1], costs[i-1][j+1]); the } - for(intj =0; J < K; ++j) { -COSTS[I][J] + =min (min1[j], min2[j]); - } + } - intres =Int_max; + for(Auto C:costs.back ()) { Ares =min (res, c); at } - returnRes; - } -};
Quickly find the minimum method of removing an element in an array: Define two arrays, min1[i] and Min2[i] record the minimum interval from left to right to point I and right to left to the first I bit, then the minimum value of the first bit of the minus is the Min (Min1[i], min2[i]).
[Leetcode] Paint House I & II