514. 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.
Example
Example 1:
Input: n=3, k=2
Output: 6
Explanation:
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
Example 2:
Input: n=2, k=2
Output: 4
Explanation:
post 1, post 2
way1 0 0
way2 0 1
way3 1 0
way4 1 1
Notice
n and k are non-negative integers.
Input test data (one parameter per line)How to understand a testcase?
解法1:
这题设计得不错,我是参考网上的思路。
i = 0时,result = 0; i = 1时,result = k。
我们从左往右看,每个post的可刷方案包括2类(result = diff+same),diff就是跟前面post不同的颜色方案,same就是跟前面post相同颜色的方案。
从i=2开始,post i的diff很好算,就是post i-1的result * (k - 1),即post i-1可以刷4种颜色,那么对于4种颜色里的每一种,post i可以有3种选择。
那么post i 的same怎么算呢? 因为post i跟post i-1颜色一样的话,那么post i-1和post i-2必须颜色不一样。也就是post i的same就是post i-1的diff。
class Solution {
public:
/**
* @param n: non-negative integer, n posts
* @param k: non-negative integer, k colors
* @return: an integer, the total number of ways
*/
int numWays(int n, int k) {
if (n == 0 || k == 0) return 0;
int same = 0, diff = k;
for (int i = 2; i <= n; ++i) {
int temp = diff;
diff = (same + diff) * (k - 1);
same = temp;
}
return same + diff;
}
};
本文详细解析了PaintFence问题,这是一个经典的动态规划问题。在n个栅栏柱上使用k种颜色进行涂色,要求相邻柱子的颜色不能超过两个相同。文章提供了详细的算法思路和C++代码实现,通过动态规划求解所有可能的涂色方案。


被折叠的 条评论
为什么被折叠?



