Created
May 6, 2022 13:04
-
-
Save theabbie/d9e4209d000cc2ee9902836c9eac23f5 to your computer and use it in GitHub Desktop.
Paint Fence Solution
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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