[LeetCode276]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.

Hide Company Tags Google
Hide Tags Dynamic Programming
Hide Similar Problems (E) House Robber (M) House Robber II (M) Paint House (H) Paint House II

機智的我看見這個題目就是排列組合問題啊,哈哈哈。但並沒什麼卵用,仔細一看,no more than two fences adjacently has same colors.

所以啊,最多可以有兩個相鄰的fence有同樣的顏色。
假如我們有3種顏色,用3種顏色塗一個fence:3種方法。塗2個fence:每個fence有三種選擇,所以有6種方法。但塗3個fence的時候就不是了。對於前兩個fence每個都有3種選擇,但對於最後一個fence, 有兩種情況:
前兩個要是是一樣的顏色,它只能有兩種選擇。
前兩個不一樣,則有三種選擇。
具體實例如下:
這裏寫圖片描述

所以我們可以知道,對於當前C fence. 兩種選擇:
1. for previous two fences are same:

case1=(k1)same

2. for previous two fences are different:
case2=kdifferent

Then the total ways to paint three fences w/ three color are:
case1+case2

What if we add a new fence D?

For D:

newSame=oldDiff

newDiff=oldSame(k1)+oldDiff(k1)=(k1)(oldSame+oldDiff)

code:

class Solution {
public:
    int numWays(int n, int k) {
        if(!k ||!n ) return 0;
        if(n == 1) return k;
        int diff = k*(k-1); //last two posts are different;
        int same = k; // last two posts are same.
        for(int i = 2; i<n; ++i){
            int newSame = diff;
            int newDiff = (k-1) * (same + diff);
            diff = newDiff;
            same = newSame;
        }
        return same + diff;
    }
};

可以把code寫簡單一點。。比如:

class Solution {
public:
    int numWays(int n, int k) {
        if(!k ||!n ) return 0;
        if(n == 1) return k;
        int diff = k*(k-1); //last two posts are different;
        int same = k; // last two posts are same.
        for(int i = 2; i<n; ++i){
          int newSame = diff;
          diff = (k-1) * (diff + same);
          same = newSame;
        }
        return same + diff;
    }
};
發佈了109 篇原創文章 · 獲贊 0 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章