LeetCode: 276. Paint Fence
Summary
Return the number of valid ways to paint n fence posts using k colors.
Rules:
- Every post must be painted exactly one color.
- There cannot be three or more consecutive posts with the same color.
Approach
Use dynamic programming with two states:
diff[i]: number of ways to paint up to postiwhere postihas a different color from posti-1.same[i]: number of ways to paint up to postiwhere postihas the same color as posti-1.
Transitions:
diff[i] = (diff[i-1] + same[i-1]) * (k - 1)same[i] = diff[i-1]
Why:
- To make post
idifferent, choose any coloring fromi-1and then choose one ofk-1different colors. - To make post
ithe same, posti-1must already be different fromi-2; otherwise we would create three consecutive posts with the same color.
Function
Initialization:
n: number of postsk: number of colors- If
n == 1, returnk. diff = [k](for the first post, allkcolors are valid)same = [0]
For each i in range(n - 1):
diff[i + 1] = (diff[i] + same[i]) * (k - 1)same[i + 1] = diff[i]
return diff[-1] + same[-1]
Edge case:
- If
k == 1andn >= 3, the answer is0(three consecutive posts would have the same color). - If
n <= 2, values are still valid under the rule.
Complexity
Time complexity: O(N), where N is the number of posts.
Space complexity: O(N) for diff and same.