[leetcode] 276. Paint Fence 解题报告
来源:互联网 发布:vm安装linux虚拟机 编辑:程序博客网 时间:2024/06/05 07:32
题目链接:https://leetcode.com/problems/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.
思路: 题意说的是不能有超过连续两个相同的颜色, 也就是说最多有两个相邻柱子染同样颜色.
所以在染一个柱子的时候, 要考虑是否和上一个柱子颜色相同.
如果和上一个相同的话那么上一个有多少种和上上次不同的染色方案, 那么当前柱子也有多少种染色方案.
如果和上一个不同的话那么染色方案就为(k-1)*(之前总共多少染色方案).
代码如下:
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, diff = (k-1)*total; total = same + diff; } return total; }};参考: https://leetcode.com/discuss/85147/complete-explanation-o-n-time-o-1-space
0 0
- [leetcode] 276. Paint Fence 解题报告
- [Leetcode] 276. Paint Fence 解题报告
- LeetCode 276. Paint Fence
- LeetCode 276. Paint Fence
- 【dp】leetcode 276. Paint Fence
- [leetcode] 265. Paint House II 解题报告
- [leetcode] 256. Paint House 解题报告
- [Leetcode] 256. Paint House 解题报告
- [Leetcode] 265. Paint House II 解题报告
- LeetCode 276. Paint Fence(篱笆涂色)
- Leetcode 276. Paint Fence (经典DP)
- Leetcode 276. Paint Fence (Easy) (cpp)
- Leetcode——276.Paint Fence
- **LeetCode-Paint Fence
- [leetcode 276] Paint Fence
- leetcode Paint Fence
- LeetCode 题解(243) : Paint Fence
- 【编程】【leetcode】276 Paint Fence
- Bullet物理引擎在OpenGL中的应用
- 我是刘杰,欢迎参观我的博客
- hdu1061(快速幂取余)
- Android ImageSlider实现广告轮播
- json-schema-core(liuhailong翻译)
- [leetcode] 276. Paint Fence 解题报告
- 扫扫土,开工啦~
- docker+node+Cordova 多平台流媒体直播系统 一 centos6.5 源码编译安装node5.8(1)
- [leetcode] 288. Unique Word Abbreviation 解题报告
- ASUS TR-N14U固件中继小白教程
- L18函數:靈活即強大
- Rain
- 关于Java的Boolean.getBoolean方法
- [leetcode] 170. Two Sum III - Data structure design 解题报告