276-栅栏涂色

2019-06-06  本文已影响0人  饮酒醉回忆

栅栏涂色

题目

There is a fence with n posts, each post can be painted with one of the k colors.</br></br>
You have to paint all the posts such that no more than two adjacent fence posts have the same color.</br></br>
Return the total number of ways you can paint the fence.</br></br>
Note:</br></br>
n and k are non-negative integers.

有一个栅栏有n个栏杆,每个栏杆可以被涂成k个颜色中的一个.你必须要在保证最多相邻的两个栏杆是同一个颜色的情况下涂完所有的栏杆.你需要返回你涂完栏杆的所有方式的总数.

提示:n和k都是非负的整数

思路

使用动态规划来解决

递推式:第三根柱子要不和第一根柱子不是一个颜色,要不和第二根柱子不是一个颜色,所以和第一根柱子颜色不一样的概率是k-1乘以第一根柱子的概率

和第二根柱子颜色不一样的概率是k-1乘以第二根柱子的概率,同时如果和第一根柱子颜色相同,则已经包含在与第二根柱子颜色不同里面,反之亦然,所以相加就是总的概率

代码

public class Solution {
    public int numWays(int n, int k) {
        int[] dp = new int[]{0,k,k*k,0};
        if(n <= 2){
            return dp[n];
        }
        for(int i = 3;i<=n;i++){
            dp[3] = (k-1) * (dp[1] + dp[2]);
            dp[1] = dp[2];
            dp[2] = dp[3];
        }
        return dp[3];
    }
}
上一篇 下一篇

猜你喜欢

热点阅读