问题描述
lintcode表述有问题,原文是“必须保证任意两个相邻的柱子颜色不同,应该表述为“不能有连续三个柱子颜色相同”。
参考
LintCode:栅栏染色
参考里改掉的表述感觉也不对,还是应该说“不能有连续三个柱子颜色相同”。
笔记
在改掉问题表述的情况下:
假设buff[i]为有i个柱子时的染色方案。可以分为两种情况:
1. 最后两个柱子颜色相同。
前i-2个柱子已经有buff[i-2]种方案了,第i-1个和第i个柱子取相同的颜色,但是要和i-2个柱子不同,有(k-1)种取法。
2. 最后两个柱子颜色不同。
前i-1个柱子符合要求,已经有buff[i-1]种方案了,第i个柱子的颜色要和第i-1个柱子颜色不同,还有(k-1)种方案。
由此,状态转移方程为:
buff[i] = buff[i-1] * (k-1) + buff[i-2] * (k-1);
初始条件:
buff[1] = k; buff[2] = k*k;
代码
采用自底向上的方法。
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) {
// Write your code here
if (n == 0)
return 0;
if (n == 1)
return k;
if (n == 2)
return k*k;
int pre = k;
int now = k*k;
for (int i = 3; i <= n; i++)
{
int tmp = now;
now = (pre+now) * (k-1);
pre = tmp;
}
return now;
}
};