Skip to content

Commit 8460438

Browse files
committed
add house-robber solution
1 parent 5ddf84f commit 8460438

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

house-robber/jongwanra.py

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
"""
2+
[Problem]
3+
https://leetcode.com/problems/house-robber/description/
4+
"""
5+
6+
class Solution(object):
7+
"""
8+
[Brain Storming]
9+
같은 날에, 인접한 집을 털면 안된다.
10+
하루에 털 수 있는 최대 금액을 구하는 문제.
11+
12+
1 <= nums.length <= 100
13+
nums.length가 최대 100이기 때문에,
14+
DFS로 문제를 접근해도 풀 수 있는 문제라고 생각한다.
15+
16+
각 집을 넣는 경우와 안넣는 경우 인접한 경우를 따져서 최대 금액을 구해보자.
17+
18+
[Complexity]
19+
Time: 집을 터는 경우, 안 터는 경우 2^100.. -> Time Limit Exceeded 발생
20+
Space: O(N) 재귀 호출 스택의 길이도 비례하여 길어짐.
21+
"""
22+
def rob1(self, nums):
23+
answer = 0
24+
visited = [False] * len(nums)
25+
26+
def dfs(depth, sum):
27+
# nonlocal nums
28+
nonlocal answer
29+
nonlocal visited
30+
31+
32+
if depth == len(nums):
33+
answer = max(answer, sum)
34+
print(sum, visited)
35+
return
36+
37+
# 다음 집을 포함한 경우
38+
if depth == 0 or not visited[depth - 1]:
39+
visited[depth] = True
40+
dfs(depth + 1, sum + nums[depth])
41+
42+
# 다음 집을 포함하지 않은 경우
43+
visited[depth] = False
44+
dfs(depth + 1, sum)
45+
46+
dfs(0, 0)
47+
return answer
48+
49+
def rob(self, nums):
50+
"""
51+
다른 사람의 풀이
52+
DFS + Memoization 기법을 활용한다.
53+
ref: https://www.algodale.com/problems/house-robber/
54+
55+
[Complexity]
56+
Time: O(N)
57+
Space: O(N)
58+
59+
"""
60+
cache = {}
61+
def dfs(depth):
62+
if depth in cache:
63+
return cache[depth]
64+
if depth >= len(nums):
65+
cache[depth] = 0
66+
return cache[depth]
67+
68+
cache[depth] = max(nums[depth] + dfs(depth + 2), dfs(depth + 1))
69+
return cache[depth]
70+
71+
return dfs(0)
72+
73+
74+
sol = Solution()
75+
print(sol.rob([1, 2, 3, 1]))
76+
print(sol.rob([2,7,9,3,1]))
77+
78+
# Edge Case
79+
print(sol.rob([1]) == 1)
80+
print(sol.rob([183,219,57,193,94,233,202,154,65,240,97,234,100,249,186,66,90,238,168,128,177,235,50,81,185,165,217,207,88,80,112,78,135,62,228,247,211]))
81+

0 commit comments

Comments
 (0)