# [LeetCode276]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.

Hide Tags Dynamic Programming
Hide Similar Problems (E) House Robber (M) House Robber II (M) Paint House (H) Paint House II


1. for previous two fences are same:

case1=(k1)same

2. for previous two fences are different:
case2=kdifferent

Then the total ways to paint three fences w/ three color are:
case1+case2

What if we add a new fence D?

For D:

newSame=oldDiff

newDiff=oldSame(k1)+oldDiff(k1)=(k1)(oldSame+oldDiff)

code:

class Solution {
public:
int numWays(int n, int k) {
if(!k ||!n ) return 0;
if(n == 1) return k;
int diff = k*(k-1); //last two posts are different;
int same = k; // last two posts are same.
for(int i = 2; i<n; ++i){
int newSame = diff;
int newDiff = (k-1) * (same + diff);
diff = newDiff;
same = newSame;
}
return same + diff;
}
};

class Solution {
public:
int numWays(int n, int k) {
if(!k ||!n ) return 0;
if(n == 1) return k;
int diff = k*(k-1); //last two posts are different;
int same = k; // last two posts are same.
for(int i = 2; i<n; ++i){
int newSame = diff;
diff = (k-1) * (diff + same);
same = newSame;
}
return same + diff;
}
};