Skip to content

Commit 33ff0d4

Browse files
Add files via upload
1 parent dd03825 commit 33ff0d4

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed

House Robber II/House_Robber_II.cpp

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
// Runtime: 4 ms, faster than 100.00% of C++ online submissions for House Robber II.
2+
// Memory Usage: 9.1 MB, less than 31.74% of C++ online submissions for House Robber II.
3+
4+
class Solution
5+
{
6+
public:
7+
int rob(vector<int>& nums)
8+
{
9+
if (nums.size() == 0)
10+
return 0;
11+
else if (nums.size() == 1)
12+
return nums[0];
13+
else if (nums.size() == 2)
14+
return max(nums[0], nums[1]);
15+
else
16+
{
17+
int temp1 = nums[0] + helper(nums, 2, nums.size() - 2);
18+
int temp2 = nums[1] + helper(nums, 3, nums.size() - 1);
19+
int temp3 = nums[2] + helper(nums, 4, nums.size() - 1);
20+
21+
return max(max(temp1, temp2), temp3);
22+
}
23+
}
24+
private:
25+
int helper(vector<int>& nums, int start, int end)
26+
{
27+
if (start > end)
28+
return 0;
29+
30+
int *res = new int[nums.size()]();
31+
32+
// 边界初始化
33+
res[end] = nums[end];
34+
res[end - 1] = max(nums[end], nums[end - 1]);
35+
res[end - 2] = max(nums[end] + nums[end - 2], nums[end - 1]);
36+
37+
for (int i = end - 3; i >= start; i--)
38+
res[i] = max(nums[i] + res[i + 2], nums[i + 1] + res[i + 3]);
39+
40+
int finres = res[start];
41+
delete[] res;
42+
return finres;
43+
}
44+
};

House Robber II/House_Robber_II.py

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# Runtime: 40 ms, faster than 41.70% of Python3 online submissions for House Robber II.
2+
# Memory Usage: 13.2 MB, less than 6.73% of Python3 online submissions for House Robber II.
3+
4+
class Solution:
5+
def rob(self, nums: List[int]) -> int:
6+
if len(nums) is 0:
7+
return 0
8+
elif len(nums) is 1:
9+
return nums[0]
10+
elif len(nums) is 2:
11+
return max(nums[0], nums[1])
12+
else:
13+
return max(
14+
nums[0] + self.helper(nums, 2, len(nums) - 2),
15+
nums[1] + self.helper(nums, 3, len(nums) - 1),
16+
nums[2] + self.helper(nums, 4, len(nums) - 1),
17+
)
18+
def helper(self, nums, start, end):
19+
if start > end:
20+
return 0
21+
res = [0 for i in range(len(nums))]
22+
23+
res[end] = nums[end]
24+
res[end - 1] = max(nums[end], nums[end - 1])
25+
res[end - 2] = max(nums[end] + nums[end - 2], nums[end - 1])
26+
27+
for i in range(end - 3, start - 1, -1):
28+
res[i] = max(nums[i] + res[i + 2], nums[i + 1] + res[i + 3])
29+
30+
return res[start]

0 commit comments

Comments
 (0)