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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|
// map存储累加和. 时间复杂度O(n+k), SC: O(n*2) 自顶向下
class Solution {
public:
int dfs(int num, unordered_map<int, int>& sum, vector<int>& dp) {
if (num == 0) return 0;
if (num == 1) {
return sum[1];
}
if (dp[num] != -1) return dp[num];
dp[num] = max(dfs(num-1, sum, dp), sum[num] + dfs(num-2, sum, dp));
return dp[num];
}
int deleteAndEarn(vector<int>& nums) {
int max_num = 1e4;
vector<int> dp(max_num+1, -1);
unordered_map<int, int> sum(max_num+1); // {i: sum of i} when i equals the element in nums
for (int& num: nums) {
sum[num] += num;
}
return dfs(max_num, sum, dp);
}
};
// 改成vectror以后。 DFS+记忆化 时间复杂度O(n+k), SC: O(n)
class Solution {
public:
int dfs(int num, vector<int>& sum, vector<int>& dp) {
if (num == 0) return 0;
if (num == 1) {
return sum[1];
}
if (dp[num] != -1) return dp[num];
dp[num] = max(dfs(num-1, sum, dp), sum[num] + dfs(num-2, sum, dp));
return dp[num];
}
int deleteAndEarn(vector<int>& nums) {
int max_num = 1e4;
vector<int> dp(max_num+1, -1);
vector<int> sum(max_num+1, 0);
for (int& num: nums) {
sum[num] += num;
}
return dfs(max_num, sum, dp);
}
};
// 自底向上 DP
class Solution {
public:
int deleteAndEarn(vector<int>& nums) {
const int max_num = 1e4;
vector<int> dp(max_num+1, 0);
vector<int> sum(max_num+1); // {i: sum of i} when i equals the element in nums
for (int& num: nums) {
sum[num] += num;
}
dp[1] = sum[1], dp[2] = max(sum[1], sum[2]);
for (int i=3; i<=max_num; i++) {
dp[i] = max(dp[i-1], dp[i-2] + sum[i]);
}
return max(dp[max_num], dp[max_num - 1]);
}
};
|