198. 打家劫舍
为保证权益,题目请参考 198. 打家劫舍(From LeetCode).
解决方案1
CPP
C++
#include <iostream>
#include <algorithm>
#include <cmath>
#include <vector>
using namespace std;
class Solution
{
public:
int rob(vector<int> &nums)
{
if (nums.size() == 0)
{
return 0;
}
else if (nums.size() == 1)
{
return nums[0];
}
else
{
vector<int> dp(nums.size(), 0);
dp[0] = nums[0];
dp[1] = max(nums[0], nums[1]);
for (int i = 2; i < nums.size(); i++)
{
dp[i] = max(dp[i - 1], nums[i] + dp[i - 2]);
}
return dp[nums.size() - 1];
}
}
};
int main()
{
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39