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.
Example:
Input: n = 3, k = 2 Output: 6 Explanation: Take c1 as color 1, c2 as color 2. All possible ways are: post1 post2 post3 ----- ----- ----- ----- 1 c1 c1 c2 2 c1 c2 c1 3 c1 c2 c2 4 c2 c1 c1 5 c2 c1 c2 6 c2 c2 c1
這道題讓我們粉刷籬笆,有n個部分需要刷,有k種顏色的油漆,規定了不能有超過連續兩根柱子是一個顏色,也就意味着第三根柱子要么根第一個柱子不是一個顏色,要么跟第二根柱子不是一個顏色,問總共有多少種刷法。那么首先來分析一下,如果 n=0 的話,說明沒有需要刷的部分,直接返回0即可,如果n為1的話,那么有幾種顏色,就有幾種刷法,所以應該返回k,當 n=2 時, k=2 時,可以分兩種情況來統計,一種是相鄰部分沒有相同的,一種相同部分有相同的顏色,那么對於沒有相同的,對於第一個格子,有k種填法,對於下一個相鄰的格子,由於不能相同,所以只有 k-1 種填法。而有相同部分顏色的刷法和上一個格子的不同顏色刷法相同,因為下一格的顏色和之前那個格子顏色刷成一樣的即可,最后總共的刷法就是把不同和相同兩個刷法加起來,參見代碼如下:
解法一:
class Solution { public: int numWays(int n, int k) { if (n == 0) return 0; int same = 0, diff = k; for (int i = 2; i <= n; ++i) { int t = diff; diff = (same + diff) * (k - 1); same = t; } return same + diff; } };
下面這種解法和上面那方法幾乎一樣,只不過多了一個變量,參見代碼如下:
解法二:
class Solution { public: int numWays(int n, int k) { if (n == 0) return 0; int same = 0, diff = k, res = same + diff; for (int i = 2; i <= n; ++i) { same = diff; diff = res * (k - 1); res = same + diff; } return res; } };
Github 同步地址:
https://github.com/grandyang/leetcode/issues/276
類似題目:
參考資料:
https://leetcode.com/problems/paint-fence/
https://leetcode.com/problems/paint-fence/discuss/71156/O(n)-time-java-solution-O(1)-space
https://leetcode.com/problems/paint-fence/discuss/178010/The-only-solution-you-need-to-read