LeetCode 276. Paint Fence

本文探讨了一个有趣的涂色问题:给定n个柱子和k种颜色,要求相邻柱子的颜色不能完全相同超过两个,计算所有可能的涂色方案数量。通过递推公式解决了这一问题,并详细解释了算法思路。

摘要生成于 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. 需要提取的信息:相邻不同和相邻相同之间的关系!例如:前n个柱子最右边相邻相同的组合有same种,不相同的有diff种,则第n+1根柱子如果刷和左边颜色不同的组合diff=(same+diff)*(k-1),刷左侧相同的组合same=previous diff.

int numWays(int n, int k) {
    //主要搞清两种情况之间的迭代关系!!!
    if(n==0) return 0;
    int diff=k,same=0;
    for(int i=2;i<=n;i++){
        int pre=diff;//previous diff;
        diff=(same+diff)*(k-1);
        same=pre;
    }
    return diff+same;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值