Skip to content

Commit 288366e

Browse files
committed
feat: house-robber 풀이 추가 (Memoization)
1 parent 9f7fc53 commit 288366e

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

house-robber/unpo88.py

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
class Solution:
2+
def rob(self, nums: list[int]) -> int:
3+
hash_value = {}
4+
5+
def dfs(start):
6+
if start in hash_value:
7+
return hash_value[start]
8+
9+
if not start < len(nums):
10+
hash_value[start] = 0
11+
else:
12+
hash_value[start] = max(nums[start] + dfs(start+2), dfs(start+1))
13+
return hash_value[start]
14+
15+
return dfs(0)
16+
17+
"""
18+
================================================================================
19+
풀이 과정
20+
================================================================================
21+
22+
1. 양 옆을 제외한 숫자들의 합을 구해야하네?
23+
2. 첫 번째를 선택하면 → 세 번째 ~ N번째 들의 부분합을 구하는 것
24+
3. 두 번째를 선택하면 → 네 번째 ~ N번째 들의 부분합을 구하는 것
25+
4. 뭔가 재귀적으로 구할 수 있을 것 같은데..?
26+
5. 첫 번째 선택한 것과 두 번째 선택한 것 중 어느것이 더 큰지 비교해보면 될 것 같은데?
27+
6. 첫 번째를 선택한 것은 → nums[0] + 재귀(nums[2:])
28+
7. 두 번째를 선택한 것은 → 재귀(nums[1:])
29+
8. 그럼 재귀함수의 로직은 어떻게 되어야하지?
30+
31+
32+
[1차 시도] 순수 재귀 - 시간 초과
33+
────────────────────────────────────────────────────────────────────────────────
34+
9. 기본적인 재귀 구조 구현
35+
36+
def dfs(start):
37+
if start >= len(nums):
38+
return 0
39+
return max(nums[start] + dfs(start + 2), dfs(start + 1))
40+
41+
return dfs(0)
42+
43+
10. 시간 초과가 발생했네?
44+
45+
46+
11. 중간 결과값들을 저장하고 있어야할 것 같은데
47+
12. 해싱으로 저장해놓고 있어보자
48+
49+
hash_value = {}
50+
51+
def dfs(start):
52+
if start in hash_value:
53+
return hash_value[start]
54+
55+
if not start < len(nums):
56+
hash_value[start] = 0
57+
else:
58+
hash_value[start] = max(nums[start] + dfs(start+2), dfs(start+1))
59+
return hash_value[start]
60+
61+
return dfs(0)
62+
63+
13. 정상적으로 통과되는 것 확인 완료
64+
"""

0 commit comments

Comments
 (0)