Skip to content

Commit f31ac9b

Browse files
refactor 276
1 parent ff793c6 commit f31ac9b

File tree

1 file changed

+19
-14
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+19
-14
lines changed
Lines changed: 19 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
package com.fishercoder.solutions;
22

3-
/**There is a fence with n posts, each post can be painted with one of the k colors.
3+
/**
4+
* 276. Paint Fence
5+
6+
There is a fence with n posts, each post can be painted with one of the k colors.
47
58
You have to paint all the posts such that no more than two adjacent fence posts have the same color.
69
@@ -10,19 +13,21 @@
1013
n and k are non-negative integers.*/
1114

1215
public class _276 {
13-
public int numWays(int n, int k) {
14-
if (n == 0) {
15-
return 0;
16-
} else if (n == 1) {
17-
return k;
18-
}
19-
int sameColorCnt = k;
20-
int diffColorCnt = k * (k - 1);
21-
for (int i = 2; i < n; i++) {
22-
int temp = diffColorCnt;
23-
diffColorCnt = (diffColorCnt + sameColorCnt) * (k - 1);
24-
sameColorCnt = temp;
16+
public static class Solution1 {
17+
public int numWays(int n, int k) {
18+
if (n == 0) {
19+
return 0;
20+
} else if (n == 1) {
21+
return k;
22+
}
23+
int sameColorCnt = k;
24+
int diffColorCnt = k * (k - 1);
25+
for (int i = 2; i < n; i++) {
26+
int temp = diffColorCnt;
27+
diffColorCnt = (diffColorCnt + sameColorCnt) * (k - 1);
28+
sameColorCnt = temp;
29+
}
30+
return sameColorCnt + diffColorCnt;
2531
}
26-
return sameColorCnt + diffColorCnt;
2732
}
2833
}

0 commit comments

Comments
 (0)