forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhaklee.py
More file actions
79 lines (58 loc) ยท 2.43 KB
/
haklee.py
File metadata and controls
79 lines (58 loc) ยท 2.43 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
"""TC: O(n + e), SC: -
๋
ธ๋ ๊ฐ์ n๊ฐ, ์ฃ์ง ๊ฐ์ e๊ฐ
์์ด๋์ด:
๋ฌธ์ ์ค๋ช
๋ถํฐ๊ฐ deepcopy๋ฅผ ํ๋ผ๋ ๊ฒ์ด๋ ๋ด์ฅํจ์๋ฅผ ์จ์ deepcopy๋ฅผ ํด์ฃผ์.
SC:
- ๋ด์ฅํจ์๊ฐ ํ์ํ ๊ณต๊ฐ๋ค์ ๋ฐ๋ก ์ ๊ด๋ฆฌํด์ฃผ์ง ์์๊น? ์๋ง ๋ณ์๋ฅผ ์ฝ๊ณ ๊ทธ๋๋ก ๋ฆฌํด๊ฐ์ผ๋ก ๋ฐ๊ฟ์ค๋ฏ.
- ๊ทธ๋ ๋ค๋ฉด ์ถ๊ฐ์ ์ผ๋ก ๊ด๋ฆฌํ๋ ๊ณต๊ฐ์ ํ์ ์๋ค.
TC:
- deepcopy๋ ํ์ํ ์ ๋ณด๋ฅผ ๊ทธ๋๋ก ๋ค deepcopy ๋ฐ ๋ฟ์ด๋ค. ์๋ง node ๊ฐ์ + edge ๊ฐ์์ ๋น๋กํด์ ์๊ฐ์ด
๊ฑธ๋ฆด๊ฒ ๊ฐ๋ค. O(n + e).
"""
"""
# Definition for a Node.
class Node:
def __init__(self, val = 0, neighbors = None):
self.val = val
self.neighbors = neighbors if neighbors is not None else []
"""
import copy
from typing import Optional
class Solution:
def cloneGraph(self, node: Optional["Node"]) -> Optional["Node"]:
return copy.deepcopy(node)
"""TC: O(e), SC: O(e)
๋
ธ๋ ๊ฐ์ n๊ฐ, ์ฃ์ง ๊ฐ์ e๊ฐ
์์ด๋์ด:
dfs ๋๋ฉด์ ๋
ธ๋๋ค์ ๋ฉ๋ชจํด๋์. neighbors์ ํน์ ๋
ธ๋๋ฅผ ์ถ๊ฐํด์ผ ํ ๋ ๋ฉ๋ชจ์ ์์ผ๋ฉด ๋ฐ๋ก ๊ฐ์ ธ๋ค
์ฐ๊ณ , ์์ผ๋ฉด ์๋ก ๋ง๋ค์ด์ ๋ฉ๋ชจ์ ๋
ธ๋๋ฅผ ์ถ๊ฐํ๋ค.
SC:
- ๋
ธ๋ ์ด n๊ฐ๊ฐ memo์ ์ฌ๋ผ๊ฐ๋ค. O(n).
- ๊ฐ ๋
ธ๋๋ง๋ค neighbor๊ฐ ์๋ค. ๊ฐ edge๋ง๋ค neighbor ๋ฆฌ์คํธ๋ค์ ์ด ์์ดํ
๊ฐ์์ 2๊ฐ์ฉ ๊ธฐ์ฌํ๋ค. O(e).
- ๋ํ๋ฉด O(n + e). ์ฆ, ๋ ์ค ๋ ํฐ ๊ฐ์ด ๊ณต๊ฐ๋ณต์ก๋๋ฅผ ์ง๋ฐฐํ๋ค.
...๊ณ ์๊ฐํ๋ ๊ฒ์ด ์ผ์ฐจ์ ์ธ ๋ถ์์ธ๋ฐ, ์ฌ๊ธฐ์ ๋ ๋์๊ฐ ์ ์๋ค.
- ์ฃผ์ด์ง ์กฐ๊ฑด์ ๋ฐ๋ฅด๋ฉด ์ฐ๋ฆฌ์๊ฒ ์ฃผ์ด์ง ๊ทธ๋ํ๋ connected graph๋ค. ์ฆ, ์ฃ์ง ๊ฐ์๊ฐ n-1๊ฐ ์ด์์ด๋ค.
- ์ฆ, O(n) < O(e)๊ฐ ๋ฌด์กฐ๊ฑด ์ฑ๋ฆฝํ๋ฏ๋ก, O(e) < O(n + e) < O(e + e) = O(e). ์ฆ, O(e).
TC:
- SC์ ๋น์ทํ ๋ฐฉ์์ผ๋ก ๋ถ์ ๊ฐ๋ฅ. O(e).
"""
"""
# Definition for a Node.
class Node:
def __init__(self, val = 0, neighbors = None):
self.val = val
self.neighbors = neighbors if neighbors is not None else []
"""
from typing import Optional
class Solution:
def cloneGraph(self, node: Optional["Node"]) -> Optional["Node"]:
if node is None:
return node
memo = {}
def dfs(node):
if node not in memo:
new_node = Node(node.val, [])
memo[node] = new_node
new_node.neighbors = [dfs(i) for i in node.neighbors]
return memo[node]
return dfs(node)