LeetCode 276. Paint Fence

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

注意check corner case, e.g. n == 0, return 0. k == 0, return 0.

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 }

类似Paint HouseHouse RobberNumber of Ways to Paint N × 3 Grid.

posted @ 2016-03-05 04:40  Dylan_Java_NYC  阅读(490)  评论(0编辑  收藏  举报