[Leetcode] 276. Paint Fence 解题报告
来源:互联网 发布:中国人口普查数据 编辑:程序博客网 时间:2024/06/05 00:46
题目:
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; }};
阅读全文
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
- HDU 5543 Pick The Sticks【三维dp】
- 图片的Base64编码
- 试简介视频编码技术?——知乎大神神回答
- [NOIP2017模拟]切蛋糕
- uio驱动编写 实例2 //增加了中断部分
- [Leetcode] 276. Paint Fence 解题报告
- php图片下载至本地
- sourceInsight添加支持UTF-8的插件
- HTTP 请求方式: GET和POST的比较
- SAP MM-SD-FI-PS-PM模块常用增强总结
- C++ 相对 C 的新特性
- 心怀逐浪,设计随行
- 关于一道简单的Java 基础面试题的剖析: short s1=1;s1 = s1 +1会报错吗?
- cJSON 使用