GfG QA is closing soon... Please refer PRACTICE or GfG now on wards !!

Coin change problem recursive top down dp help

I am able to get solution for brute force and bottom up dp. BUt for top down recursive dp it's not working. Please help.

# include<iostream>
using namespace std;

// Returns the count of ways we can sum  s[0...m-1] coins to get sum n

//brute-force
int coin( int s[], int m, int n )
{
    // If n is 0 then there is 1 solution (do not include any coin)
    if (n == 0)
        return 1;

    // If n is less than 0 then no solution exists
    if (n < 0)
        return 0;

    // If there are no coins and n is greater than 0, then no solution exist
    if (m <=0 && n >= 1)
        return 0;

    // count is sum of subproblems' solution after current solution (i) excludes s[m-1] (ii) includes s[m-1]
    return coin( s, m - 1, n ) + coin( s, m, n-s[m-1] );
}

int coinTd(int arr[],int m,int n,int *dp[])
{
if (n < 0)
        return 0;
if(m<0)
    return 0;

    if(dp[n][m]>INT_MIN)
    return dp[n][m];

if(n==0)
    return dp[n][m]=1;

if (m ==0 && n >= 1)
        return dp[n][m]=0;

return dp[n][m]=coinTd(arr,m,n-arr[m],dp)+coinTd(arr,m-1,n,dp);
}

void coinTdHelp(int arr[], int m,int n)
{

    int **dp = new int* [n+1];

    for(int i=0;i<=n;i++)
    dp[i] = new int [m];

    for(int i=0;i<=n;i++)
    for(int j=0;j<=m-1;j++)
    dp[i][j] = INT_MIN;


    cout << coinTd(arr,m-1,n,dp)<<"\n";

    for(int i=0;i<=n;i++)
    {for(int j=0;j<=m-1;j++)
        {cout<<dp[i][j];}
cout<<"\n";
        }
    delete(dp);
}


//bottom-up DP
int coinBu( int s[], int m, int n )
{
    int i, j, x, y;

    // We need n+1 rows as the table is constructed in bottom up manner using
    // the base case 0 value case (n = 0)
    int table[n+1][m];

    // Fill the entries for 0 value case (n = 0)
    for (i=0; i<m; i++)
        table[0][i] = 1;

    // Fill rest of the table enteries in bottom up manner
    for (i = 1; i < n+1; i++)
    {
        for (j = 0; j < m; j++)
        {
            // Count of solutions including s[j]
            if(i-s[j] >= 0)
            x= table[i - s[j]][j];
            else
            x=0;

            // Count of solutions excluding s[j]
            if(j >= 1)
                y=table[i][j-1];
            else
                y=0;

            // total count
            table[i][j] = x + y;
        }
    }
    return table[n][m-1];
}


// Driver program to test above function
int main()
{
    int i, j;
    int arr[] = {1, 2, 3};
    int m = sizeof(arr)/sizeof(arr[0]);
    cout<<coinBu(arr, m, 4)<<"\n";
   coinTdHelp(arr,m,4);
   // cout<<coin(arr,m,4);
    cout<<"\n";

    return 0;
}

 

asked Mar 4, 2017 by Satish Srinivas
...