[Leetcode] 276. Paint Fence 解题报告

探讨了一道经典的动态规划问题——如何为一系列围栏柱子涂色,使得相邻柱子的颜色不同或最多只有两根柱子颜色相同,进而求解总的涂色方案数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

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.

思路

这是一道简单的动态规划题目。在染一个柱子的时候,要考虑是否和上一个柱子的颜色相同,有两种方案:1)如果和上一个柱子染同一种颜色,那么取决于上一个柱子有多少种和上上个柱子不同的染色方案;2)如果染和上一个不同的颜色,那么染色方案就有(k - 1) * (之前总共有多少种方案)。由于状态转移方程中dp[i]只和前两个状态有关,所以可以将空间复杂度降低到O(1),时间复杂度则是最优的O(n)。

代码

class Solution {
public:
    int numWays(int n, int k) {
        if(n == 0 || k == 0 || (k == 1 && n > 2)) {
            return 0;
        }
        int same = 0, diff = k, total = k;
        for(int i = 2; i <= n; ++i) {
            same = diff;                // the i-th is the same as the (i-1)-th
            diff = (k - 1) * total;     // the i-th is different from the (i-1)-th
            total = same + diff;
        }
        return total;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值