|
2 | 2 |
|
3 | 3 | /**
|
4 | 4 | * Paint House 2
|
| 5 | + * https://leetcode.com/problems/paint-house/ |
5 | 6 | * https://leetcode.com/problems/paint-house-ii/
|
6 | 7 | */
|
7 | 8 | public class PaintHouse {
|
8 |
| - public int minCost(int[][] costs) { |
| 9 | + |
| 10 | + public int minCostTopDownPainHouse1(int[][] costs) { |
| 11 | + if (costs.length == 0) { |
| 12 | + return 0; |
| 13 | + } |
| 14 | + int[][] dp = new int[costs.length][3]; |
| 15 | + return minCostUtil(costs, 0, -1, dp); |
| 16 | + } |
| 17 | + |
| 18 | + private int minCostUtil(int[][] costs, int house, int prevColor, int[][] dp) { |
| 19 | + if (house == costs.length) { |
| 20 | + return 0; |
| 21 | + } |
| 22 | + int min = Integer.MAX_VALUE; |
| 23 | + for (int i = 0; i <= 2; i++) { |
| 24 | + if (i == prevColor) { |
| 25 | + continue; |
| 26 | + } |
| 27 | + int val; |
| 28 | + if (dp[house][i] != 0) { |
| 29 | + val = dp[house][i]; |
| 30 | + } else { |
| 31 | + val = costs[house][i] + minCostUtil(costs, house + 1, i, dp); |
| 32 | + dp[house][i] = val; |
| 33 | + } |
| 34 | + min = Math.min(min, val); |
| 35 | + } |
| 36 | + return min; |
| 37 | + } |
| 38 | + |
| 39 | + public int minCostBottomUpPaintHouse2(int[][] costs) { |
9 | 40 | if (costs.length == 0 || costs[0].length == 0) {
|
10 | 41 | return 0;
|
11 | 42 | }
|
@@ -64,6 +95,6 @@ private Pair findMinSecondMin(int[] input) {
|
64 | 95 | public static void main(String args[]) {
|
65 | 96 | PaintHouse ph = new PaintHouse();
|
66 | 97 | int[][] input = {{1, 2, 1}, {1, 4, 5}, {2, 6, 1}, {3, 3, 2}};
|
67 |
| - System.out.println(ph.minCost(input)); |
| 98 | + System.out.println(ph.minCostBottomUpPaintHouse2(input)); |
68 | 99 | }
|
69 | 100 | }
|
0 commit comments