276. Paint Fence

题目链接: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;
    }
}

lulouch13
13 声望6 粉丝