lintcode 514. 栅栏染色

这次是我最喜欢的DP题

514. 栅栏染色

我们有一个栅栏,它有n个柱子,现在要给柱子染色,有k种颜色可以染。
必须保证不存在超过2个相邻的柱子颜色相同,求有多少种染色方案。

样例

n = 3, k = 2, return 6

      post 1,   post 2, post 3
way1    0         0       1 
way2    0         1       0
way3    0         1       1
way4    1         0       0
way5    1         0       1
way6    1         1       0

注意事项

nk都是非负整数

题目要求给柱子染色,要求不能超过2个以上颜色相同,也就是说,2个是可以相同的,说得再通俗点,就是

连续的3个柱子颜色不能相同

假设现在是第X个柱子,一共有dp(x)种方法,前面2个柱子是dp(x-1)和dp(x-2),前面的柱子肯定是满足要求的

可以按x和x-1是否相同分为2种情况

(1)x和x-1不同

由于x和x-1不同,所以不用考虑x-2的情况,dp[x]=(k-1)*dp[x-1]

扫描二维码关注公众号,回复: 2582863 查看本文章

(2)x和x-1相同

这个情况下就必须保证x和x-1的颜色和x-2不同,dp=(k-1)*dp[x-2]

综合起来dp[x]=(dp[x-1]+dp[x-2])*(k-1)

前2个柱子颜色选择可以手写出来

dp{0:0,1:k,2:k*k}

class Solution:
    """
    @param n: non-negative integer, n posts
    @param k: non-negative integer, k colors
    @return: an integer, the total number of ways
    """
    def numWays(self, n, k):
        # write your code here
        dp = [0, k, k * k]
        if n <= 2:
            return dp[n]
        if k == 1 and n >= 3:
            return 0
        for i in xrange(2, n):
            dp.append((k - 1) * (dp[-1] + dp[-2]))

        return dp[-1]

猜你喜欢

转载自blog.csdn.net/wzngzaixiaomantou/article/details/81415167
514
今日推荐