Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit efe28b3

Browse files
author
Tushar Roy
committed
Update paint house
1 parent 18c377d commit efe28b3

File tree

1 file changed

+33
-2
lines changed

1 file changed

+33
-2
lines changed

‎src/com/interview/dynamic/PaintHouse.java‎

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,41 @@
22

33
/**
44
* Paint House 2
5+
* https://leetcode.com/problems/paint-house/
56
* https://leetcode.com/problems/paint-house-ii/
67
*/
78
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) {
940
if (costs.length == 0 || costs[0].length == 0) {
1041
return 0;
1142
}
@@ -64,6 +95,6 @@ private Pair findMinSecondMin(int[] input) {
6495
public static void main(String args[]) {
6596
PaintHouse ph = new PaintHouse();
6697
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));
6899
}
69100
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /