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
思路:
本题特点是求方案总数,可以使用DP来解决。下面按照标准DP解题思路:
1. 定义状态:
dp[i]表示i个fence漆k中颜色有多少种方案
2. 转移方程:
题目要求最多不能超过两个相邻的fence的颜色相同,那只要保证f[i]与前一个f[i-1]或者与f[i-2]不一样,那可以得到状态转移方程:
dp[i] = dp[i - 1] * (k - 1) + dp[i - 2] * (k - 1)
为什么是乘k-1,是因为只要和dp[i - 1]的颜色不一样,那就剩余k - 1种可能;
3. 初始条件和边界情况
如果fence数量或者k等于0的话,那只有0种情况;
dp[0] = k # 0表示1个fence的时候的所有涂色情况
dp[1] = k * k # 1表示2个fence的时候所有涂色情况
4. 计算顺序
dp[0], dp[1], dp[2]...
class Solution:
def numWays(self, n: int, k: int) -> int:
if n == 0 or k == 0:
return 0
dp = [0 for _ in range(n)]
dp[0] = k
dp[1] = k * k
for i in range(2, n):
dp[i] = dp[i - 1] * (k - 1) + dp[i - 2] * (k - 1)
return dp[n - 1]
5. 滚动数组优化
根据动态转移方程可以分析到,当前i时刻的状态只与i-1和i-2两个时刻有关,那就可以使用滚动数据优化,滚动更新三个变量的数据。
class Solution:
def numWays(self, n: int, k: int) -> int:
if n == 0 or k == 0:
return 0
dp = [0] * 3
dp[0] = k
dp[1] = k * k
for i in range(2, n):
dp[i % 3] = dp[(i - 1) % 3] * (k - 1) + dp[(i - 2) % 3] * (k - 1)
return dp[(n - 1) % 3]