-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path312. Burst Balloons.cpp
74 lines (56 loc) · 2.02 KB
/
312. Burst Balloons.cpp
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
64
65
66
67
68
69
70
71
72
73
74
// -----Approach 1: Memoization ------------------------------------------------------------
/*
Problem Link: https://leetcode.com/problems/burst-balloons/
Time: 544 ms (Beats 49.11%), Space: 10.5 MB (Beats 25.91%)
*/
class Solution {
private:
int sol(int i, int j, vector<int>& nums, vector<vector<int>>& dp){
if(i > j) return 0;
if(dp[i][j] != -1) return dp[i][j];
int mx= -1e9;
for(int idx=i; idx<=j; idx++){
int cost= nums[i-1] * nums[idx] * nums[j+1] + sol(i, idx-1, nums, dp) + sol(idx+1, j, nums, dp);
mx= max(mx, cost);
}
return dp[i][j]= mx;
}
public:
int maxCoins(vector<int>& nums) {
// try to bend logic by solving from bottom up, to get intuition
// otherwise the subproblems would be dependent
int n= nums.size();
vector<vector<int>> dp(n+1, vector<int>(n+1, -1));
nums.insert(nums.begin(), 1);
nums.push_back(1);
return sol(1, n, nums, dp);
}
};
// -----Approach 2: Tabulation ------------------------------------------------------------
/*
Problem Link: https://leetcode.com/problems/burst-balloons/
Time: 359 ms (Beats 83.95%), Space: 10.4 MB (Beats 64.51%)
*/
class Solution {
public:
int maxCoins(vector<int>& nums) {
// try to bend logic by solving from bottom up, to get intuition
// otherwise the subproblems would be dependent
int n= nums.size();
vector<vector<int>> dp(n+2, vector<int>(n+2, 0)); // n+2 due to idx+1
nums.insert(nums.begin(), 1);
nums.push_back(1);
for(int i=n; i>=1; i--){
for(int j=1; j<=n; j++){
if(i > j) continue;
int mx= -1e9;
for(int idx=i; idx<=j; idx++){
int cost= nums[i-1] * nums[idx] * nums[j+1] + dp[i][idx-1] + dp[idx+1][j];
mx= max(mx, cost);
}
dp[i][j]= mx;
}
}
return dp[1][n];
}
};