Subscribed unsubscribe Subscribe Subscribe

Takefumi Yamamura's blog

This blog is for my memorandum.

Takefumi Yamamura's b!og

This blog is for my memorandum

276. Paint Fence (Google, LeetCode)

Problem

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.

Note: n and k are non-negative integers.

How to solve

Firstly, I think this is the easy math problem, but actually this is dynamic programming. I have to clarify on "no more than two adjacent fence posts" There can be multiple 2 adjacent posts have same colors--a more clear way to put it is "no 3 adjacent posts have the same color"

for 4 post 2 color case (0 for black, 1 for red) 0011 is a valid solution, 0001 is not

code