[LeetCode] 265. Paint House II
There are a row of n houses, each house can be painted with one of the k colors. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color.
The cost of painting each house with a certain color is represented by a
n x k
cost matrix. For example, costs[0][0]
is the cost of painting house 0 with color 0; costs[1][2]
is the cost of painting house 1 with color 2, and so on... Find the minimum cost to paint all houses.
Note:
All costs are positive integers.
All costs are positive integers.
Follow up:
Could you solve it in O(nk) runtime?
Could you solve it in O(nk) runtime?
Thought process:
- Sub-problem: find the minimum cost to paint houses up to current house.
- Function: f[i][j] = min(f[i - 1][k] where k != j) + costs[i][j].
- Initialization: modify the costs matrix directly.
- Answer: min(f[costs.length][j]).
Follow-up:
Currently this solution takes O(nk^2). Iterating all combinations takes O(nk). Finding the minimum among colors takes O(k). The optimization here is to reduce finding minimum to O(1). I do not need to find minimum for every color, because all I need is the minimum and the next minimum. If current color is the same as the previous color, which happens to have the minimum cost, I can just use the second minimum.
Solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | class Solution { public int minCostII(int[][] costs) { if (costs.length == 0) { return 0; } int first = -1; int second = -1; for (int i = 0; i < costs.length; i++) { int previous1 = first; int previous2 = second; first = -1; second = -1; for (int j = 0; j < costs[i].length; j++) { if (j == previous1) { costs[i][j] += previous2 < 0 ? 0 : costs[i - 1][previous2]; } else { costs[i][j] += previous1 < 0 ? 0 : costs[i - 1][previous1]; } if (first < 0 || costs[i][j] < costs[i][first]) { second = first; first = j; } else if (second < 0 || costs[i][j] < costs[i][second]) { second = j; } } } return costs[costs.length - 1][first]; } } |
Time complexity: O(nk).
Great notes, really helpful
ReplyDeleteraviAdend_o-Washington Curtis Bethea https://wakelet.com/wake/_PrSmXy1rOUWP1gMozDh-
ReplyDeletescisoggata