码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode: Paint Fence

时间:2015-12-25 06:26:55      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:

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种可能性。假设dp[1]是第一根柱子及之前涂色的可能性数量,dp[2]是第二根柱子及之前涂色的可能性数量,则dp[3]=(k-1)*dp[1] + (k-1)*dp[2]

递推式有了,下面再讨论下base情况,所有柱子中第一根涂色的方式有k中,第二根涂色的方式则是k*k,因为第二根柱子可以和第一根一样。

 1 public class Solution {
 2     public int numWays(int n, int k) {
 3         // 当n=0时返回0
 4         int dp[] = {0, k , k*k, 0};
 5         if(n <= 2){
 6             return dp[n];
 7         }
 8         for(int i = 2; i < n; i++){
 9             // 递推式:第三根柱子要么根第一个柱子不是一个颜色,要么跟第二根柱子不是一个颜色
10             dp[3] = (k - 1) * (dp[1] + dp[2]);
11             dp[1] = dp[2];
12             dp[2] = dp[3];
13         }
14         return dp[3];
15     }
16 }

 

Leetcode: Paint Fence

标签:

原文地址:http://www.cnblogs.com/EdwardLiu/p/5074815.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!