0

Coding Problem Link i have coded the brute-force recursion without any DP.

public class coinChangeCombination {
    public static void main(String[] args){
        int[] coins = {2, 3, 5, 6};
        int target = 7;
        System.out.println(coinRecursive(0, target, coins, 0));
    }    

    //basic recursion
    public static int coinRecursive(int current, int target, int[] coins, int index){
        if(current > target) return 0;
        if(current == target) return 1;
        int count = 0;
        for(int i = index; i < coins.length; i++){
            int res = coinRecursive(current+coins[i], target, coins, i);
            count += res;
        }
        return count;
    }
}

Now since two variables are getting changed in recursion, we will need a 2-d array to store the intermediate results but what does each cell of the 2-d array represent? Like in Fibonacci DP when we take a 1-d array, each cell represents the Fibonacci of that index, likewise what does our 2-d array in this question represent? i am unable to think the meaning behind it, whats the intuition?

Progman
  • 16,827
  • 6
  • 33
  • 48
  • This is a Unbounded Knapsack problem: for each coin, we can put as many times as we want. DP comes in as the handy data structure. dp[i][j] : the number of combinations to make up amount j by using the first i types of coins State transition: not using the ith coin, only using the first i-1 coins to make up amount j, then we have dp[i-1][j] ways. – Daniel Hao Jun 13 '21 at 15:04

1 Answers1

0

A bottom-up approach for this coin changes problem in Java to demo the DP way:

class Solution {
    public int change(int amount, int[] coins) {
        int n = coins.length;
        int[][] dp = new int[2][amount + 1];
        for (int i = 0; i <= n; i++)
            dp[i % 2][0] = 1; //  one way to change 0 amount
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= amount; j++) {
                dp[i % 2][j] = dp[(i - 1) % 2][j]; // skip ith coin
                if (j >= coins[i - 1])
                    dp[i % 2][j] += dp[i % 2][j - coins[i - 1]]; // use ith coin
            }
        }
        return dp[n % 2][amount];
    }
}
Daniel Hao
  • 4,922
  • 3
  • 10
  • 23