原题
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
Accepted
40,248
Submissions
111,560
解法
动态规划.
参考: Leetcode 刷题 - 276 - Paint Fence
当n=1时, 结果为k
当n = 2时, 分为两种情况, 颜色与上一步相同same, 颜色与上一步不同diff, 此时, same为k, diff为k*(k-1)
当n > 3时, 根据题意, 不能有超过两个颜色相同的篱笆, 那么颜色与上一步相同时的情况只能用上一步的diff推导, 个数为diff. 颜色与上一步不同时, 可以用所有之前的情况, 个数为(same+diff)*(k-1).
最后返回same + diff即可.
代码
class Solution:
def numWays(self, n: 'int', k: 'int') -> 'int':
# base case
if n == 0: return 0
if n == 1: return k
# when n == 2
same, diff = k, k*(k-1)
for i in range(3, n+1):
same, diff = diff, (same + diff)*(k-1)
return same + diff
本文详细解析了LeetCode题目276涂漆栅栏的动态规划解法,阐述了如何计算在n个栅栏柱上使用k种颜色进行涂漆,且不超过两个相邻栅栏柱颜色相同的总方案数。文章通过具体实例解释了状态转移方程,以及如何通过递推计算得到最终结果。
428

被折叠的 条评论
为什么被折叠?



