Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit81e31c3

Browse files
committed
added O(min(m,n)) solution to Unique paths
1 parent9dd9c1d commit81e31c3

File tree

1 file changed

+17
-1
lines changed

1 file changed

+17
-1
lines changed

‎Unique Paths.py

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,25 @@
11
classSolution:
2+
23
defuniquePaths(self,m,n):
34
ways= [[1]foriinrange(m)]
45
foriinrange(1,n):
56
ways[0].append(1)
67
foriinrange(1,m):
78
forjinrange(1,n):
89
ways[i].append(ways[i-1][j]+ways[i][j-1])
9-
returnways[m-1][n-1]
10+
returnways[m-1][n-1]
11+
12+
# it's pascal's triangle, we can get result by computing C(m,n), we can
13+
# achieve O(min(m,n))
14+
15+
defuniquePaths_2(self,m,n):
16+
ifm<n:
17+
returnself.uniquePaths(n,m)
18+
ifm==1andn==1:
19+
return1
20+
m,n,res=m+n-2,n-1,1
21+
ifn> (m/2):
22+
n=m-n
23+
foriinxrange(n):
24+
res=res* (m-i)/ (i+1)
25+
returnres

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp