Painting Fence - Stuck to find out generalized version

356 Views Asked by At

Problem Statement: There is a fence with n posts, each post can be painted with one of the k colors. You have to paint all the posts such that no more than two adjacent fence posts have the same color. Return the total number of ways you can paint the fence.

My logic: 1st

Number of post :1

Number of color :1

Then I can paint the post using one way

2nd

Number of post:2

Number of Color: 1

Number of way I can paint it 1

If number of color: 2

Number of way I can paint the fence:

Say I have two color Red and Blue

I can colored the fence

  1. Red Red

  2. Blue Blue

  3. Red Blue

Now if the number of color :3(Red, Blue, Green)

  1. Red Red

  2. Blue Blue

  3. Green Green

  4. Red Blue

  5. Red Green

  6. Blue Green

So, No. of way 6.

If I increase number of color and the posts then I get some other combination.

The generalized combination may be : 3*2*1 (redbluegreen), If I consider I have k color so the formula become k*(k-1)*(k-2).

So, k*(k-1)*(k-2) Number of way.

Am I thinking correctly? I cannot find out a generalized version for n post and k color of this problem.

Please help me to find out a general formula of this question.

1

There are 1 best solutions below

0
On

Replace the colors with numbers $0,1,\dots,k-1$. For every numbering of the $n$ fenceposts, consider its sequence of differences, which is a sequence of $n-1$ numbers equalling the difference modulo $k$ between each pair of adjacent fenceposts. A fencepost coloring is legal if any only if its sequence of differences does not contain two adjacent zeroes.

For example, when $k=4$, the difference sequence of $01223121$ is $1101213$.

How many sequences of $n-1$ numbers in $\{0,1,\dots,k-1\}$ contain no two adjacent zeroes? Letting $a_{n-1}$ be this number, you can show $a_n=(k-1)a_{n-1}+(k-1)a_{n-2}$. The first summand counts sequences which do not end with zero, and the second counts ones which do. This lets you compute $a_n$ recursively.

Finally, every fencepost coloring is uniquely determined by its first element and its difference sequence, so there are $ka_{n-1}$ difference sequences.