problem:
There is a fence with n posts, each post can be painted with one of the K colors.
You had to paint all the posts such that no more than and the 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.
Wrong solution:
Public classSolution { Public intNumways (intNintk) {if(n = = 0 | | k = = 0) return0; if(n = = 1) returnK; intTotal =K; intCount = 1; while(Count <k) { total*= k-1; Count++; } returnTotal ; }}
MistakeAnalysis:
for arranging the painting which have no more than the sussive post share the same color. It means we were allowed to make, neighboring posts share the same color!
Analysis:
The problem of asking how many ways to DoSomething is usually very easy!and it could always be solved through dynamic programming. You just need to carefully design the transitional function acoording to characteristics or certain restrictions. We know forEach post, it could differ or same as its previous post ' s color.Assume:differ_count:represents The current post with different color with its previous post (the painting ways) same_c Ount:represents the current post share the same color with its previous post (the painiting ways) We could has following T Rasitinao Functiondiffer_count (i)= Differ_count (i-1) * (k-1) + same_count (i-1) * (k-1) Same_count (i)= Differ_count (i-1)//cause the current post must has the same color with post i-1, thus we could only use the same as that Differ_count (i-1)
Base Case:2 is a perfect base Case forUse to start, since it had simple same_count and differ_count;
Solution:
Public classSolution { Public intNumways (intNintk) {if(n = = 0 | | k = = 0) return0; if(n = = 1) returnK; intSame_count =K; intDiffer_count = k * (k-1); for(inti = 3; I <= N; i++) { inttemp =Differ_count; Differ_count= Differ_count * (k-1) + Same_count * (k-1); Same_count=temp; } returnSame_count +Differ_count; }}
[leetcode#276] Paint Fence