Skip to content

Latest commit

 

History

History
63 lines (41 loc) · 1.68 KB

276. Paint-Fence.md

File metadata and controls

63 lines (41 loc) · 1.68 KB

Description

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.

Example:

Input: n = 3, k = 2
Output: 6
Explanation: Take c1 as color 1, c2 as color 2. All possible ways are:

            post1  post2  post3
 -----      -----  -----  -----
   1         c1     c1     c2
   2         c1     c2     c1
   3         c1     c2     c2
   4         c2     c1     c1
   5         c2     c1     c2
   6         c2     c2     c1

python solution

思路

动态规划问题。设f(i)为共i个柱子的方案数。对于第i个柱子,它有2种可能:和第i − 1个柱子颜色相同,和第i − 1个柱子颜色不同。则共i个柱子的方案数为这2种可能对应的方案数的和。

  • 和第i−1个柱子颜色相同:那么i, i − 1的颜色只要和i − 2不同就可以了,共有k−1个颜色,对应的方案数为(k − 1) ∗ f(i − 2)
  • 和第i−1个柱子颜色不同:那么i的颜色只要和i−1不同就可以了,共有k−1个颜色,对应的方案数为(k − 1) ∗ f(i − 1)

综上f(i) = (k − 1) ∗ f(i − 2) + (k − 1) ∗ f(i − 1)

初始条件:f(1) = k, f(2) = k^2

class Solution:
    def numWays(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: int
        """
        res = [k, k**2]
        while n>len(res):
            res.append((k - 1) * (res[-1] + res[-2]))
        return res[n-1] if n > 0 else 0