【发布时间】:2016-12-13 19:53:11
【问题描述】:
我在 lintcode 上遇到了这个问题,并且我已经阅读了两个过去的解决方案,但它们对我来说都没有意义。
问题如下:
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.
给定 n =3,k=2,返回 6。
所以我理解的部分是如果 n=0(我们有 0 个帖子)或 k = 0(我们有 0 个绘画),我们不能绘画任何东西,所以返回 0
如果 n == 1,帖子可以用 K 种方式绘制,所以返回 k
当n为2时,如果相邻的柱子相等,我们可以用K*1的方式绘制它,如果相邻的柱子不同,我们可以用K*(K-1)的方式绘制它。
如果 n ==3 或更多:相同的相邻颜色将是:K * 1 * K-1 * 1 * K-1... 不同的是:K * K-1 * K-1 ....
我该如何从这里开始?我见过一个人再次用 [0, k, 2k, and 0] 创建一个矩阵,另一个人将“不同颜色”简化为 (k+k*(k-1)) * (k-1) 但我不知道他们中的任何一个是如何跳到结论的那一步
编辑:一个人的解决方案如下:
class Solution:
# @param {int} n non-negative integer, n posts
# @param {int} k non-negative integer, k colors
# @return {int} an integer, the total number of ways
def numWays(self, n, k):
# Write your code here
table = [0, k, k*k, 0]
if n <= 2:
return table[n]
# recurrence equation
# table[posts] = (color - 1) * (table[posts - 1] + table[posts - 2])
for i in range(3, n + 1):
table[3] = (k - 1) * (table[1] + table[2])
table[1], table[2] = table[2], table[3]
return table[3]
但我不明白为什么他的表格末尾有 [0],以及他如何建立递归方程
【问题讨论】:
标签: algorithm