leetcode-198-House-Robber

描述


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.

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.

分析


把问题抽象一下就是:在一个非负的序列中选择一些元素,使得和最大,但不能选择相邻的元素。动态规划问题,公式是 maxv[i] = max(maxv[i-2]+nums[i], maxv[i-1]);

解决方案1(Python)


1
2
3
4
5
6
7
8
9
10
11
class Solution(object):
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
length = len(nums)
result = [0 for _ in range(length+2)]
for i in range(2, length+2):
result[i] = max(result[i-1], result[i-2]+nums[i-2])
return result[-1]

解决方案2(C++)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
int rob(vector<int>& nums) {
int n = nums.size();
if(0 == n) {
return 0;
}
if(1 == n) {
return nums[0];
}
vector<int> maxv(n, 0);
maxv[0] = nums[0];
maxv[1] = max(nums[0], nums[1]);
for(int i = 2; i < n; i++) {
maxv[i] = max(maxv[i-2]+nums[i], maxv[i-1]);
}
return maxv[n-1];
}
};

解决方案3(Golang)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
func rob(nums []int) int {
numsLen := len(nums)
if numsLen == 0 {
return 0
}
if numsLen == 1 {
return nums[0]
}
dp := make([]int, numsLen + 1)
dp[1] = nums[0]

for i := 2; i <= numsLen; i++ {
dp[i] = max(dp[i-1], dp[i-2] + nums[i-1])
}
return dp[numsLen]
}

func max(a, b int) int {
if a >= b {
return a
}
return b
}

相关问题


题目来源