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;
}
}

评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论