Skip to content

Commit bbd60d9

Browse files
authored
Update unique-paths.py
1 parent 411ea8e commit bbd60d9

File tree

1 file changed

+32
-9
lines changed

1 file changed

+32
-9
lines changed

Python/unique-paths.py

Lines changed: 32 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,39 @@
1-
# Time: O(m * n)
2-
# Space: O(m + n)
1+
# Time: O(m + n)
2+
# Space: O(1)
33

44
class Solution(object):
5-
# @return an integer
65
def uniquePaths(self, m, n):
6+
"""
7+
:type m: int
8+
:type n: int
9+
:rtype: int
10+
"""
11+
def nCr(n, r): # Time: O(n), Space: O(1)
12+
if n-r < r:
13+
r = n-r
14+
c = 1
15+
for k in xrange(1, r+1):
16+
c *= n-k+1
17+
c //= k
18+
return c
19+
20+
return nCr((m-1)+(n-1), n-1)
21+
22+
23+
# Time: O(m * n)
24+
# Space: O(m + n)
25+
class Solution2(object):
26+
def uniquePaths(self, m, n):
27+
"""
28+
:type m: int
29+
:type n: int
30+
:rtype: int
31+
"""
732
if m < n:
8-
return self.uniquePaths(n, m)
9-
ways = [1] * n
33+
m, n = n, m
1034

35+
dp = [1]*n
1136
for i in xrange(1, m):
1237
for j in xrange(1, n):
13-
ways[j] += ways[j - 1]
14-
15-
return ways[n - 1]
16-
38+
dp[j] += dp[j-1]
39+
return dp[n-1]

0 commit comments

Comments
 (0)