LintCode 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.

樣例:

Given n=3, k=2 return 6

     post 1,   post 2, post 3
way1    0         0       1 
way2    0         1       0
way3    0         1       1
way4    1         0       0
way5    1         0       1
way6    1         1       0

分析:

影響第n種的顏色的是第n-1與第n-2種顏色的,因此可能性都為k-1種
因此得到如下遞推式:maxWays[n] = (k - 1) * (maxWays[n - 1] + maxWays[n - 2]);

public class Solution {
    /**
     * @param n non-negative integer, n posts
     * @param k non-negative integer, k colors
     * @return an integer, the total number of ways
     */
   public int numWays(int n, int k) {
        if(n == 0 || k == 0)
            return 0;
        if(n == 1)
            return k;
        
        int[] maxWays = new int[n + 1];
        maxWays[0] = 0;
        maxWays[1] = k;
        maxWays[2] = k * k;
        for(int i = 3;i <= n;i ++)
        {
            maxWays[i] = (k - 1) * (maxWays[i - 1] + maxWays[i - 2]);
        }
        
        return maxWays[n];
    }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容