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.
Idea: DP.
Set P (i) to indicate the number of cases from the first poster to the Zhang Hai report.
Initial condition: P (0) = 0,p (1) = K.
When n=2, there are two cases: 1) The second Zhang Hai the color of the newspaper differs from the first, altogether K * (k-1) kind of situation; 2) The colors of the two posters are the same, altogether the K-type situation. So P (2) = k + k* (k-1).
When N>2, it is assumed that the current is the Zhang Hai report, there are two cases: 1) The Zhang Hai of the first and the previous color, the total is P (i-1) * (k-1) of the situation; 2) The Zhang Hai is the same as the color of the previous one, which is the case of P (i-2) * (k-1).
So P (i) = P (i-2) * (k-1) + P (i-1) * (k-1).
In the implementation, we do not need to use an array to record all the results, we only need P (i-2) and P (i-1) values, so you can use the variable slow to record the value of P (i-2), with fast to record the value of P (i-1).
1 classSolution {2 Public:3 intNumways (intNintk) {4 if(n = =0)returnN;5 if(n = =1)returnK;6 intslow =K;7 intFast = slow + slow * (K-1);8 for(inti =3; I <= N; i++) {9 intCur = slow * (K-1) + Fast * (K-1);Tenslow =fast; OneFast =cur; A } - returnfast; - } the};
Paint Fence--Leetcode