-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmerge_elements.cpp
71 lines (69 loc) · 1.44 KB
/
merge_elements.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
/*
Problem Link - https://www.interviewbit.com/problems/merge-elements/
vector<vector<int>> dp;
vector<int> pre;
int recursor(vector<int> A, int i, int j)
{
if(i==j) return 0;
if(dp[i][j] != -1) return dp[i][j];
int ans=INT_MAX;
for(int k=i; k<j; k++)
{
ans=min(ans, recursor(A, i, k)+recursor(A, k+1, j)+pre[j+1]-pre[i]);
}
return dp[i][j] = ans;
}
int topdown(vector<int> A)
{
int a = A.size();
dp.clear();
dp.resize(a, vector<int> (a, -1));
pre.clear();
int summ=0;
pre.push_back(summ);
for(int i=0; i<a; i++)
{
summ+=A[i];
pre.push_back(summ);
}
return recursor(A, 0, a-1);
}
int Solution::solve(vector<int> &A) {
return topdown(A);
}
*/
#include <bits/stdc++.h>
using namespace std;
vector<vector<int>> dp;
vector<int> pre;
int recursor(vector<int> A, int i, int j)
{
if(i==j) return 0;
if(dp[i][j] != -1) return dp[i][j];
int ans=INT_MAX;
for(int k=i; k<j; k++)
{
ans=min(ans, recursor(A, i, k)+recursor(A, k+1, j)+pre[j+1]-pre[i]);
}
return dp[i][j] = ans;
}
int topdown(vector<int> A)
{
int a = A.size();
dp.clear();
dp.resize(a, vector<int> (a, -1));
pre.clear();
int summ=0;
pre.push_back(summ);
for(int i=0; i<a; i++)
{
summ+=A[i];
pre.push_back(summ);
}
return recursor(A, 0, a-1);
}
int main()
{
vector<int> A = {1,2,3,4};
return topdown(A);
}