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.
样例:
Given n=3, k=2 return 6
1 2 3 4 5 6 7
post 1, post 2, post 3 way1 001 way2 010 way3 011 way4 100 way5 101 way6 110
public class Solution { /** * @param n non-negative integer, n posts * @param k non-negative integer, k colors * @return an integer, the total number of ways */ public int numWays(int n, int k) { if(n == 0 || k == 0) return0; if(n == 1) return k; int[] maxWays = new int[n + 1]; maxWays[0] = 0; maxWays[1] = k; maxWays[2] = k * k; for(int i = 3;i <= n;i ++) { maxWays[i] = (k - 1) * (maxWays[i - 1] + maxWays[i - 2]); } return maxWays[n]; } }