題目連接:https://leetcode.com/problems...數組
dp來解,subproblem是:
diff[i]: number of paints when current i is different from i - 1,
same[i]: number of paints when current i is same as i-1
因此dp方程爲:diff[i] = diff[i-1] * (k-1) + same[i-1] * (k-1)
,same[i] = diff[i-1]
,滾動數組優化優化
public class Solution { public int numWays(int n, int k) { if(n == 0) return 0; if(k == 0) return 0; int same = 0; int diff = k; for(int i = 1; i < n; i++) { int temp = diff; diff = (k-1) * (same + diff); same = temp; } return same + diff; } }