Skip to content

Commit 7c9a992

Browse files
add a solution for 276
1 parent 49a9ebd commit 7c9a992

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

src/main/java/com/fishercoder/solutions/firstthousand/_276.java

+22
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,28 @@
22

33
public class _276 {
44
public static class Solution1 {
5+
/**
6+
* Credit: https://leetcode.com/problems/paint-fence/editorial/
7+
* 1. base case: dp[0] = k; dp[1] = k * k;
8+
* 2. recurrence: dp[i] = dp[i - 1] * (k - 1) + dp[i - 2] * (k - 1)
9+
* dp[i - 1] * (k - 1) means to use a different color than the (i-1)th post to paint ith post
10+
* dp[i - 2] * (k - 1) means to use the same color as the (i - 1)th post, but different from (i - 2)th post to paint the ith post
11+
*/
12+
public int numWays(int n, int k) {
13+
int[] dp = new int[n];
14+
dp[0] = k;
15+
dp[1] = k * k;
16+
for (int i = 2; i < n; i++) {
17+
dp[i] = dp[i - 1] * (k - 1) + dp[i - 2] * (k - 1);
18+
}
19+
return dp[n - 1];
20+
}
21+
}
22+
23+
public static class Solution2 {
24+
/**
25+
* The above solution could be further optimized to use O(1) space.
26+
*/
527
public int numWays(int n, int k) {
628
if (n == 0) {
729
return 0;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package com.fishercoder;
2+
3+
import com.fishercoder.solutions.firstthousand._276;
4+
import org.junit.jupiter.api.BeforeEach;
5+
import org.junit.jupiter.api.Test;
6+
7+
import static org.junit.jupiter.api.Assertions.assertEquals;
8+
9+
public class _276Test {
10+
private static _276.Solution1 solution1;
11+
private static _276.Solution2 solution2;
12+
13+
@BeforeEach
14+
public void setup() {
15+
solution1 = new _276.Solution1();
16+
solution2 = new _276.Solution2();
17+
}
18+
19+
@Test
20+
public void test1() {
21+
assertEquals(6, solution1.numWays(3, 2));
22+
assertEquals(6, solution2.numWays(3, 2));
23+
}
24+
25+
}

0 commit comments

Comments
 (0)