1 public class Solution {
 2     public int numWays(int n, int k) {
 3         if (n == 0) {
 4             return 0;
 5         }
 6         if (n == 1) {
 7             return k;
 8         }
 9         
10         
11         int same = k;
12         int diff = k * (k - 1);
13         for (int i = 2; i < n; i++) {
14             int tmp = diff;
15             diff = (diff + same) * (k - 1);
16             same = tmp;
17         }
18         return same + diff;
19     }
20 }

Say we have two count diff color and same color before.

When we update it, for this layer:

1. If previous two layers are same color. We only can choose DIFF color. It will be (k - 1) * same

2. If previous two layers are diff color. We can either choose DIFF color with previous one, diff * (k - 1), OR we choose SAME color as previous  diff * 1.

So new diff = same * (k - 1) + diff * ( k - 1)

new same = diff * 1;

posted on 2016-07-07 13:33  keepshuatishuati  阅读(139)  评论(0编辑  收藏  举报