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.
思路:
1. 为保证相邻的柱子最多有两个相同,可以分成两种情况讨论:相邻的两个颜色不相同,相邻的两个颜色相同。将两种情况相加。
2. 需要提取的信息:相邻不同和相邻相同之间的关系!例如:前n个柱子最右边相邻相同的组合有same种,不相同的有diff种,则第n+1根柱子如果刷和左边颜色不同的组合diff=(same+diff)*(k-1),刷左侧相同的组合same=previous diff.
int numWays(int n, int k) {
//主要搞清两种情况之间的迭代关系!!!
if(n==0) return 0;
int diff=k,same=0;
for(int i=2;i<=n;i++){
int pre=diff;//previous diff;
diff=(same+diff)*(k-1);
same=pre;
}
return diff+same;
}