原题网址:https://leetcode.com/problems/paint-fence/
There is a fence with n posts, each post can be painted with one of the k colors.
You have to paint all the posts such that no more than two adjacent fence posts have the same color.
Return the total number of ways you can paint the fence.
Note:
n and k are non-negative integers.
思路:此题有点类似炒股问题,关键在于如何模拟重复一次的情形,诀窍在于使用两个不同的状态数组,一组表示该下标处改变颜色,一组表示该下标处颜色不变。
方法:动态规划,两个状态数组,时间复杂度O(n),空间复杂度O(n)。
代码:
public class Solution {
public int numWays(int n, int k) {
if (n==0 || k==0) return 0;
if (n==1) return k;
int[] change = new int[n];
int[] duplicate = new int[n];
change[0] = k;
for(int i=1; i<n; i++) {
duplicate[i] = change[i-1];
change[i] = (change[i-1]+duplicate[i-1])*(k-1);
}
return duplicate[n-1]+change[n-1];
}
}
可以优化空间如下:
public class Solution {
public int numWays(int n, int k) {
if (n <= 0 || k <= 0) return 0;
int same = 0, diff = k;
for(int i=1; i<n; i++) {
int ns = diff;
int nd = (same+diff)*(k-1);
same = ns;
diff = nd;
}
return same + diff;
}
}

本文介绍了一种利用动态规划方法解决栅栏涂色问题的算法,限制相邻栅栏不能涂相同颜色,通过两个状态数组实现优化,最终计算出所有合法涂色方案的数量。
2691

被折叠的 条评论
为什么被折叠?



