找回密码
 立即注册

扫一扫,访问微社区

QQ登录

只需一步,快速开始

查看: 2809|回复: 0

[代码与实例] Lintcode514 Paint Fence solution 题解

4

主题

4

帖子

4

积分

贫民

积分
4
rockerrrr 发表于 2018-8-2 10:49:49 | 显示全部楼层 |阅读模式
【题目描述】
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.
Notice
n and k are non-negative integers.
我们有一个栅栏,它有n个柱子,现在要给柱子染色,有k种颜色可以染。
必须保证不存在超过2个相邻的柱子颜色相同,求有多少种染色方案。
注意事项
n和k都是非负整数

【题目链接】
www.lintcode.com/en/problem/paint-fence/

【题目解析】
DP表示第i个柱子最多的选择数。在计算DP时,考虑两种情况:
和第i-1柱子不同颜色,则可以有(k-1) * DP[i-1]个选择
和第i-1柱子相同颜色,此时要求i-1柱子和i-2柱子不同颜色(即第一种情况,只是换成了第i-1根柱子和第i-2根柱子不同颜色),所以有(k-1) * DP[i-2]个选择
因此总选择数为(k-1) * (DP[i-1] + DP[i-2])
因为只和前两个柱子相关,所以可以用滚动数组来优化空间。

【参考答案】
www.jiuzhang.com/solution/paint-fence/


简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表