Skip to content

Commit 4dc1805

Browse files
Add files via upload
1 parent 6ca34c1 commit 4dc1805

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed

House Robber/House_Robber.cpp

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
// 思路一 简单的回溯超时了
2+
// 59 / 69 test cases passed.
3+
class Solution
4+
{
5+
public:
6+
int rob(vector<int>& nums)
7+
{
8+
return helper(nums, 0);
9+
}
10+
private:
11+
int helper(vector<int>& nums, int start)
12+
{
13+
if (start >= nums.size())
14+
return 0;
15+
else if (start == nums.size() - 1)
16+
return nums[start];
17+
else
18+
return max(nums[start] + helper(nums, start + 2), nums[start + 1] + helper(nums, start + 3));
19+
}
20+
};
21+
22+
// 思路二
23+
// 自底向上的动态规划
24+
// Runtime: 4 ms, faster than 100.00% of C++ online submissions for House Robber.
25+
// Memory Usage: 9.1 MB, less than 11.45% of C++ online submissions for House Robber.
26+
class Solution
27+
{
28+
public:
29+
int rob(vector<int>& nums)
30+
{
31+
if (nums.size() == 0)
32+
return 0;
33+
34+
int *res = new int[nums.size()];
35+
36+
// 边界初始化
37+
res[nums.size() - 1] = nums[nums.size() - 1];
38+
if (nums.size() >= 2)
39+
res[nums.size() - 2] = max(nums[nums.size() - 1], nums[nums.size() - 2]);
40+
if (nums.size() >= 3)
41+
res[nums.size() - 3] = max(nums[nums.size() - 1] + nums[nums.size() - 3], nums[nums.size() - 2]);
42+
43+
for (int i = nums.size() - 4; i >= 0; i--)
44+
res[i] = max(nums[i] + res[i + 2], nums[i + 1] + res[i + 3]);
45+
46+
int finres = res[0];
47+
delete[] res;
48+
return finres;
49+
}
50+
};

House Robber/House_Robber.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# Runtime: 44 ms, faster than 34.83% of Python3 online submissions for House Robber.
2+
# Memory Usage: 13.1 MB, less than 5.00% of Python3 online submissions for House Robber.
3+
4+
class Solution:
5+
def rob(self, nums: List[int]) -> int:
6+
if len(nums) is 0:
7+
return 0
8+
9+
res = [0 for i in range(len(nums))]
10+
11+
res[-1] = nums[-1]
12+
if len(nums) >= 2:
13+
res[-2] = max(nums[-1], nums[-2])
14+
if len(nums) >= 3:
15+
res[-3] = max(nums[-1] + nums[-3], nums[-2])
16+
17+
for i in range(len(nums) - 4, -1, -1):
18+
res[i] = max(nums[i] + res[i + 2], nums[i + 1] + res[i + 3])
19+
20+
return res[0]

0 commit comments

Comments
 (0)