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.
n and k are non-negative integers.
Solution1: dp
Define two DP arrays, diff[n] and same[i].
diff[i] means the number of ways for the fence i which has different color with fence i -1.
same[i] means the number of ways if fence i has the same color with fence i - 1.
递推公式:diff[i] = (k - 1) * (same[i - 1] + diff[i - 1])Run time complexity is O(n), space complexity is O(n).
public class Solution { public int numWays(int n, int k) { if (n == 0 || k == 0) { return 0; } // i - 1 and i - 2 with the same color int[] same = new int[n]; // i - 1 and i - 2 with the different color int[] diff = new int[n]; same[0] = 0; diff[0] = k; for (int i = 1; i < n; i++) { same[i] = diff[i - 1]; diff[i] = (k - 1) * (diff[i - 1] + same[i - 1]); } return same[n - 1] + diff[n - 1]; } }Solution2:
Same logic as solution1, but constant space.
public class Solution { public int numWays(int n, int k) { if (n == 0 || k == 0) { return 0; } int preSame = 0; int preDiff = k; for (int i = 1; i < n; i++) { int same = preDiff; int diff = (k - 1) * (preDiff + preSame); preSame = same; preDiff = diff; } return preSame + preDiff; } }
No comments:
Post a Comment