[LeetCode] 276. 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.
解题思路:
用动态规划(DP),不能有超过连续两根柱子是一个颜色,也就意味着第三根柱子要么根第一个柱子不是一个颜色,要么跟第二根柱子不是一个颜色。如果不是同一个颜色,计算可能性的时候就要去掉之前的颜色,也就是k-1种可能性。假设dp[1]是第一根柱子及之前涂色的可能性数量,dp[2]是第二根柱子及之前涂色的可能性数量,则dp[3]=(k-1)*dp[1] + (k-1)*dp[2]。
递推式有了,下面再讨论下base情况,所有柱子中第一根涂色的方式有k中,第二根涂色的方式则是k*k,因为第二根柱子可以和第一根一样。
State:dp[i] // 代表粉刷到第i个桩子总共有多少种刷法
Function: dp[i] = dp[i - 1] * (k - 1) + dp[i - 2] * (k - 1)
Initialize: dp[0] = k, dp[1] = k + dp[0] * (k - 1) = k * k
Return: dp[n]
Java: Time: O(n), Space: O(n)
public class Solution { public int numWays(int n, int k) { int dp[] = new int[n + 1]; dp[0] = 0 dp[1] = k; dp[2] = k * k; if(n <= 2){ return dp[n]; } for(int i = 2; i < n; i++){ dp[i] = (k - 1) * (dp[i - 1] + dp[i - 2]); } return dp[n]; } }
Java: Time: O(n), Space: O(1)
public class Solution { public int numWays(int n, int k) { int dp[] = {0, k , k*k, 0}; if(n <= 2){ return dp[n]; } for(int i = 2; i < n; i++){ dp[3] = (k - 1) * (dp[1] + dp[2]); dp[1] = dp[2]; dp[2] = dp[3]; } return dp[3]; } }