276. Paint Fence

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;
    }
}
相关文章
相关标签/搜索