276.Paint Fence
Tags: [DP], [double_dp]
Com: {g}
Link: https://leetcode.com/problems/paint-fence/#/description
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.
Solution: DP, Double DP
class Solution(object):
def numWays(self, n, k):
"""
:type n: int
:type k: int
:rtype: int
"""
if n == 0:
return 0
if n == 1:
return k
# same[i] means: num of ways to paint (i), where (i - 1) and (i) have the same color.
# diff[i] means: num of ways to paint (i), where (i - 1) and (i) have the diff color.
same = [0 for _ in xrange(n)]
diff = [0 for _ in xrange(n)]
same[0] = same[1] = k
diff[0] = k
diff[1] = (k - 1) * same[0]
# explain above line:
# (0) painted by one color,
# so there are (k - 1) ways to paint (1),
# to make (i - 1) and (i) have different color
for i in xrange(2, n):
same[i] = diff[i - 1]
diff[i] = (k - 1) * same[i - 1] + (k - 1) * diff[i - 1]
return same[n - 1] + diff[n - 1]
Revelation:
- The explanation has been commented in code.
Note:
- Time complexity = O(n).
Time Limited Exceeded:
class Solution(object):
def numWays(self, n, k):
"""
:type n: int
:type k: int
:rtype: int
"""
if not n or not k:
return 0
return self.num_ways_helper(n, k, 0, None, None)
def num_ways_helper(self, n, k, i, pprev, prev):
# base case
if i >= n:
return 1
counter = 0
for color in xrange(k):
if pprev == prev == color:
continue
counter += self.num_ways_helper(n, k, i + 1, prev, color)
return counter
Note:
- Time complexity = O(k^n).