Explanation:

As we can paint at most two adjacent posts with same color, we can never have such a situation: For example: BBBW or WWWB or BWWW or BWWW. Here B = Black, W = White.

Let's say we start painting from left side. Posts will look like this:

|^|..|^|..|^|..|^|

Here there are 4 posts. So n = 4.

Now for painting, i = 1, Post #1, we have.

```
1. sameColor = 0 as there is no Post #(i-1)
2. diffColor = k. because we can use any 1 of the k colors.
3. total = sameColor + diffColor = 0 + k = k
```

At any given Post i, i > 1, we can have two ways

```
1. sameColor = Paint with same color as Post #(i-1)
2. diffColor = Paint with different color than Post #(i-1)
3. total = sameColor + diffColor
```

Or,

```
1. sameColor = diffColor*1 = diffColor of Post #(i-1)
2. diffColor = (k-1)*total at Post #(i-1)
3. total = sameColor + diffColor
```

For diffColor, We multiply total by k-1 because you can use any color except 1 color which was the previous.

```
class Solution {
public:
int numWays(int n, int k) {
if(k==0 || n == 0 || (n>2 && k==1) ) return 0;
int sameColor = 0;
int diffColor = k;
int total = diffColor + sameColor;
for(int i=2; i<=n; i++){
sameColor = diffColor;
diffColor = (k-1)*total;
total = (diffColor+sameColor);
}
return total;
}
};
```

Ask me anything. No question is silly.