forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChaedie.py
More file actions
53 lines (39 loc) ยท 1.47 KB
/
Chaedie.py
File metadata and controls
53 lines (39 loc) ยท 1.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
"""
1 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
Solution:
1) grid์์ 0,0์ ์ ์ธํ๊ณค ๋๋ฌํ ์ ์๋ ๋ฐฉ๋ฒ์ด left way + upper way ๊ฐฏ์๋ฐ์ ์๋ค๊ณ ์๊ฐํ๋ค.
2) ๋ฐ๋ผ์ grid๋ฅผ ์ํํ๋ฉฐ grid index์ ๊ฒฝ๊ณ๋ฅผ ๋์ด๊ฐ์ง ์์ ๊ฒฝ์ฐ left way + upper way ๊ฐฏ์๋ฅผ ๋ํด์ฃผ์๋ค.
3) ๋ง์ง๋ง grid์ ์ฐํ๋จ์ ๊ฐ์ return ํด์ฃผ์์ต๋๋ค.
Time: O(mn) (์์์ ๊ฐฏ์)
Space: O(mn) (์์์ ๊ฐฏ์)
"""
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
dp = []
for i in range(m):
dp.append([0] * n)
for i in range(m):
for j in range(n):
if i == 0 and j == 0:
dp[i][j] = 1
continue
up_value = 0 if i - 1 < 0 or i - 1 >= m else dp[i - 1][j]
left_value = 0 if j - 1 < 0 or j - 1 >= n else dp[i][j - 1]
dp[i][j] = up_value + left_value
return dp[m - 1][n - 1]
"""
* 7์ฃผ์ฐจ์ ๋ฐ์ ๋ฆฌ๋ทฐ์ฌํญ ๋ค๋ฆ๊ฒ ๋ฐ์ํฉ๋๋ค.
Solution:
1) dp๋ฅผ 1๋ก m*n ๋ฐฐ์ด๋ก ์ด๊ธฐํ
2) ์ํ๋ฅผ 1๋ถํฐ m, 1๋ถํฐ n๊น์ง๋ก ๋ณ๊ฒฝ
3) up_value, left_value ๋ฅผ Out of bounds ์ฒ๋ฆฌ ์์ด dp ๋ฐฐ์ด๋ก ๊ณ์ฐ
"""
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
dp = [[1] * n] * m
for i in range(1, m):
for j in range(1, n):
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
return dp[m - 1][n - 1]