Skip to content

Commit 41bd6c9

Browse files
committed
House Robber/ Binary Tree Right Side View
1 parent ec2984f commit 41bd6c9

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed

198 House Robber.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
'''
2+
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
3+
4+
Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.
5+
'''
6+
7+
class Solution(object):
8+
def rob(self, nums):
9+
"""
10+
:type nums: List[int]
11+
:rtype: int
12+
"""
13+
if not nums:
14+
return 0
15+
n = len(nums)
16+
if n < 2:
17+
return nums[0]
18+
dp = [0] * n
19+
dp[0] = nums[0]
20+
dp[1] = max(nums[0], nums[1])
21+
for i in range(2, n):
22+
dp[i] = max(dp[i - 1], dp[i - 2] + nums[i])
23+
return dp[-1]
24+
25+
26+
if __name__ == "__main__":
27+
assert Solution().rob([1, 2, 3, 4, 5, 6, 7]) == 16

199 Binary Tree Right Side View.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
'''
2+
Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
3+
4+
For example:
5+
Given the following binary tree,
6+
1 <---
7+
/ \
8+
2 3 <---
9+
\ \
10+
5 4 <---
11+
You should return [1, 3, 4].
12+
'''
13+
14+
# Definition for a binary tree node.
15+
class TreeNode(object):
16+
def __init__(self, x):
17+
self.val = x
18+
self.left = None
19+
self.right = None
20+
21+
22+
class Solution(object):
23+
def rightSideView(self, root):
24+
"""
25+
:type root: TreeNode
26+
:rtype: List[int]
27+
"""
28+
result = []
29+
30+
def dfs(node, level):
31+
if node is None:
32+
return
33+
if len(result) == level:
34+
result.append(node.val)
35+
if node.right:
36+
dfs(node.right, level + 1)
37+
if node.left:
38+
dfs(node.left, level + 1)
39+
40+
dfs(root, 0)
41+
return result
42+
43+
44+
if __name__ == "__main__":
45+
None

0 commit comments

Comments
 (0)