I am facing difficulty with Dynamic Programming. I was trying the trivial Coin Change problem- COIN CHANGE Problem UVa
I am trying to use top-down approach with memorization but I am getting TLE. Here is my code-
#include <bits/stdc++.h>
using namespace std;
#define ll long long
typedef vector <int > vi;
typedef vector <vi> vii;
const int maxn = 10000007;
int Set[maxn];
int Coin(int n,int m,vii & dp)
{
if(n==0)
return 1;
else if(n<0 || m<0)
return 0;
else if(dp[n][m]!=-1)
return dp[n][m];
else
{
dp[n][m]=Coin(n-Set[m],m,dp)+Coin(n,m-1,dp);
return dp[n][m];
}
}
int main()
{
int n,m=5;
Set[0]=50,Set[1]=25,Set[2]=10,Set[3]=5,Set[4]=1;
while(scanf("%d",&n)!=EOF)
{
vector <vector <int> > dp(n+1,vector<int> (m,-1));
dp[0][0]=0;
cout << Coin(n,m-1,dp) << endl;
}
}
I want to know am I doing memorization wrong or top-down will not work in this case and bottom-up approach is the only option.
dp[i][j]
; is it the number of possible ways to use coins of typej
for a money value ofi
or is it something different? – Codor 2 days ago