LeetCode Paint Fence
Posted Dylan_Java_NYC
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 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.
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 }
以上是关于LeetCode Paint Fence的主要内容,如果未能解决你的问题,请参考以下文章
leetcode276- Paint Fence- easy
[LeetCode] 276. Paint Fence 粉刷篱笆