276. Paint Fence

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.

Solution: DP

class Solution(object):
    def numWays(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: int
        """
        if n == 0:
            return 0
        if n == 1:
            return k
        same, diff = k, k * (k - 1)
        for _ in range(3, n + 1):
            same, diff = diff, (same + diff) * (k - 1)
        return same + diff

Lessons:

  • For two posts, either same color (same = k), or different (diff = k * (k - 1)).
  • For 3rd post,
    • either same color with 2nd post, which means 2nd post paints differently from 1st post, same = pre_diff
    • or different color with 2nd post, which means 2nd post can be both same and different color with 1st post, diff = pre_same + pre_diff

results matching ""

    No results matching ""