Leetcode——276.Paint Fence
来源:互联网 发布:淘宝企业店铺出售 编辑:程序博客网 时间:2024/06/15 01:22
Description
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.
Solution
public class Solution { public int numWays(int n, int k) { // 当n=0时返回0 int dp[] = {0, k , k*k, 0}; if(n <= 2){ return dp[n]; } for(int i = 2; i < n; i++){ // 递推式:第三根柱子要么根第一个柱子不是一个颜色,要么跟第二根柱子不是一个颜色 dp[3] = (k - 1) * (dp[1] + dp[2]); dp[1] = dp[2]; dp[2] = dp[3]; } return dp[3]; }}
Note: n and k are non-negative integers
复杂度
时间 O(N) 空间 O(1)
思路
这种给定一个规则,计算有多少种结果的题目一般都是动态规划,因为我们可以从这个规则中得到递推式。根据题意,不能有超过连续两根柱子是一个颜色,也就意味着第三根柱子要么根第一个柱子不是一个颜色,要么跟第二根柱子不是一个颜色。如果不是同一个颜色,计算可能性的时候就要去掉之前的颜色,也就是k-1种可能性。假设dp[1]是第一根柱子及之前涂色的可能性数量,dp[2]是第二根柱子及之前涂色的可能性数量,则dp[3]=(k-1)*dp[1] + (k-1)*dp[2]。
递推式有了,下面再讨论下base情况,所有柱子中第一根涂色的方式有k中,第二根涂色的方式则是k*k,因为第二根柱子可以和第一根一样。
复杂度
时间 O(N) 空间 O(1)
另一种解释:
分析:
由题目可以知道,最多有两个相邻的栅栏可以涂相同的颜色。
则主要思想是,如果前两根栅栏颜色相同,则第三根栅栏的颜色不能跟前两根的栅栏颜色相同,若是前两根栅栏颜色不同,则第三根栅栏颜色随便涂。综合的思想就是,第三根栅栏或者与第一根栅栏的颜色不同,或者与第二根的栅栏颜色不同。(即,包括了,可以与前两个栅栏的颜色都不同,与第一根栅栏颜色不同时,可以与第二根相同,与第二根栅栏不同的时候可以与第一根相同)。
如果用num[0]表示第一根栅栏以及之前栅栏总共可以涂色的方法数量;(栅栏数量为i时的方法数量)
num[1]表示第二根栅栏以及之前栅栏总共可以涂色的方法数量;(栅栏数量为i+1时的方法数量)
num[ 2]表示第三根以及之前总共可以涂色的方法数量
num[3] = (k-1)*num[0] + (k-1)*num[1];
以此类推到n为止。
- Leetcode——276.Paint Fence
- LeetCode 276. Paint Fence
- LeetCode 276. Paint Fence
- 【dp】leetcode 276. Paint Fence
- [leetcode] 276. Paint Fence 解题报告
- 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
- 276. Paint Fence
- Paint Fence
- Paint Fence
- [LeetCode276]Paint Fence
- CocoaPods 2016最新安装和使用说明
- NYOJ-123 士兵杀敌(四) (线段树)
- Android DataBinding(二) 事件绑定
- URL中“#” “?” &“”号的作用
- 《JAVA与模式》之适配器模式
- Leetcode——276.Paint Fence
- Hibernate小知识点(many to one ,one to one的属性解释)
- c#拼接List
- 向SQL Server中的现有表中添加具有默认值的列
- 《机器学习实战》学习笔记之k-近邻算法3
- windows server 2012将计算机图标添加到桌面
- 十二,iOS通讯录好友信息的获取
- c3p0
- java再复习——代码执行的大体流程与内存分析