Skip to content

Instantly share code, notes, and snippets.

@theabbie
Created May 6, 2022 13:04
Show Gist options
  • Save theabbie/d9e4209d000cc2ee9902836c9eac23f5 to your computer and use it in GitHub Desktop.
Save theabbie/d9e4209d000cc2ee9902836c9eac23f5 to your computer and use it in GitHub Desktop.
Paint Fence Solution
# 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.
from functools import lru_cache
class Solution:
@lru_cache(maxsize=None)
def ways(self, a, b, p, n, k):
if p == n:
return 1
ctr = 0
for i in range(k):
if a == -1 or b == -1 or len({a, b, i}) > 1:
ctr += self.ways(b, i, p + 1, n, k)
return ctr
def num_ways(self, n: int, k: int) -> int:
return self.ways(-1, -1, 0, n, k)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment