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

LeetCode Paint Fence

时间:2016-03-05 06:52:02      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:

原题链接在这里: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.

题解:

base case n == 1, 那么有k种图法. n==2时,若选择相同图法,有k种,若不同图法,有k*(k-1)种方法,总共有sameColorLastTwo + diffColorLastTwo种方法。

dp时,当到了 i 时 有两种选择,第一种 i 和 i-1不同色,那么有 i-1的总共方法 * (k-1), 就是(sameColorLastTwo + diffColorLastTwo) * (k-1);

第二种用相同色,那么 i -1 和 i-2 必须用不同色, 就是i-1的diffColorLastTwo.

最后返回两种方法的和diffColorLastTwo + sameColorLastTwo.

Time Complexity: O(n). Space: O(1).                   

AC Java:

 1 public class Solution {
 2     public int numWays(int n, int k) {
 3         if(n<=0 || k<=0){
 4             return 0;
 5         }
 6         if(n == 1){
 7             return k;
 8         }
 9         int sameColorLastTwo = k;
10         int diffColorLastTwo = k*(k-1);
11         for(int i = 3; i<=n; i++){
12             int temp = diffColorLastTwo;
13             diffColorLastTwo = (sameColorLastTwo + diffColorLastTwo) * (k-1);
14             sameColorLastTwo = temp;
15         }
16         return diffColorLastTwo + sameColorLastTwo;
17     }
18 }

 

LeetCode Paint Fence

标签:

原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/5244046.html

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