Skip to content

Commit a9510f8

Browse files
authored
Create 276. Paint Fence.java
1 parent b7a9830 commit a9510f8

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

276. Paint Fence.java

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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

Comments
 (0)