We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent b7a9830 commit a9510f8Copy full SHA for a9510f8
276. Paint Fence.java
@@ -0,0 +1,23 @@
1
+public class Solution {
2
+ public int numWays(int n, int k) {
3
+ if (n == 0 || k == 0 || (k == 1 && n >= 3)) {
4
+ return 0;
5
+ } else if (n == 1) {
6
+ return k;
7
+ } else {
8
+ int [] ways = new int[n+1];
9
+ ways[1] = k;
10
+ ways[2] = k*k;
11
+
12
+ for (int i = 3; i <= n; i++) {
13
+ // Consider 2 cases:
14
+ // - if nth post is of different color from (n-1)th post
15
+ // - if nth post is of same color from (n-1)th post, which means
16
+ // (n-1)th post is of different color from (n-2)th post
17
+ ways[i] = ways[i-1] * (k-1) + ways[i-2] * (k-1);
18
+ }
19
20
+ return ways[n];
21
22
23
+}
0 commit comments