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
思路
动态规划问题。设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