[leetcode] 276. Paint Fence @ python

本文详细解析了LeetCode题目276涂漆栅栏的动态规划解法,阐述了如何计算在n个栅栏柱上使用k种颜色进行涂漆,且不超过两个相邻栅栏柱颜色相同的总方案数。文章通过具体实例解释了状态转移方程,以及如何通过递推计算得到最终结果。

原题

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
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值