-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinCoinsLecture20.cpp
More file actions
75 lines (69 loc) · 1.81 KB
/
Copy pathMinCoinsLecture20.cpp
File metadata and controls
75 lines (69 loc) · 1.81 KB
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
75
#include <vector>
#include <iostream>
using namespace std;
int solve1(int ind,int T,vector<int> &arr,vector<vector<int>> &dp)
{
if(ind == 0)
{
if(T % arr[0] == 0) return T / arr[0];
return 1e9;
}
if(dp[ind][T] != -1) return dp[ind][T];
int notTake = solve1(ind-1,T,arr,dp);
int take = INT_MAX;
if(arr[ind] <= T) take = 1 + solve1(ind,T - arr[ind],arr,dp);
return dp[ind][T] = min(take,notTake);
}
int solve2(vector<int> &arr, int target)
{
int n = arr.size();
vector<vector<int>> dp (n,vector<int>(target+1,-1));
for(int T = 0;T<=target;T++)
{
if(T%arr[0] == 0) dp[0][T] = T / arr[0];
else dp[0][T] = 1e9;
}
for(int ind = 1;ind < n;ind++)
{
for(int T = 0;T<=target;T++)
{
int notTake = dp[ind-1][T];
int take = INT_MAX;
if(arr[ind] <= T) take = 1 + dp[ind][T-arr[ind]];
dp[ind][T] = min(take,notTake);
}
}
return dp[n-1][target];
}
int solve3(vector<int> &arr, int target)
{
int n = arr.size();
vector<int> prev(target+1,0),cur(target+1,0);
for(int T = 0;T<=target;T++)
{
if(T%arr[0] == 0) prev[T] = T / arr[0];
else prev[T] = 1e9;
}
for(int ind = 1;ind < n;ind++)
{
for(int T = 0;T<=target;T++)
{
int notTake = prev[T];
int take = INT_MAX;
if(arr[ind] <= T) take = 1 + cur[T-arr[ind]];
cur[T] = min(take,notTake);
}
prev = cur;
}
return prev[target];
}
int minimumElements(vector<int> &num, int x)
{
int n = num.size();
vector<vector<int>> dp (n,vector<int>(x+1,-1));
// int ans = solve1(n-1,x,num,dp);
// int ans = solve2(num,x);
int ans = solve3(num,x);
if(ans >= 1e9) return -1;
return ans;
}