Skip to content

Commit 3a01fa0

Browse files
committed
Create paint-fence.py
1 parent 426ab09 commit 3a01fa0

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

Python/paint-fence.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# Time: O(n)
2+
# Space: O(1)
3+
4+
# DP solution with rolling window.
5+
class Solution(object):
6+
def numWays(self, n, k):
7+
"""
8+
:type n: int
9+
:type k: int
10+
:rtype: int
11+
"""
12+
if n == 0:
13+
return 0
14+
elif n == 1:
15+
return k
16+
ways = [0] * 3
17+
ways[0] = k
18+
ways[1] = (k - 1) * ways[0] + k
19+
for i in xrange(2, n):
20+
ways[i % 3] = (k - 1) * (ways[(i - 1) % 3] + ways[(i - 2) % 3])
21+
return ways[(n - 1) % 3]
22+
23+
# Time: O(n)
24+
# Space: O(n)
25+
# DP solution.
26+
class Solution2(object):
27+
def numWays(self, n, k):
28+
"""
29+
:type n: int
30+
:type k: int
31+
:rtype: int
32+
"""
33+
if n == 0:
34+
return 0
35+
elif n == 1:
36+
return k
37+
ways = [0] * n
38+
ways[0] = k
39+
ways[1] = (k - 1) * ways[0] + k
40+
for i in xrange(2, n):
41+
ways[i] = (k - 1) * (ways[i - 1] + ways[i - 2])
42+
return ways[n - 1]

0 commit comments

Comments
 (0)