Leetcode 276. Paint Fence

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]

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值