File tree 2 files changed +47
-0
lines changed
main/java/com/fishercoder/solutions/firstthousand
test/java/com/fishercoder
2 files changed +47
-0
lines changed Original file line number Diff line number Diff line change 2
2
3
3
public class _276 {
4
4
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
+ */
5
27
public int numWays (int n , int k ) {
6
28
if (n == 0 ) {
7
29
return 0 ;
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments