2

I am new to the concepts of recursion, backtracking and dynamic programming.

I am having a hard time understanding if at all I can apply memoization to a particular recursive algorithm and if there is a relation between memoization being applicable ONLY to top down recursive algorithms. Any explanation on the same would be greatly appreciated.

The Background to this question:

I have a naive inefficient recursive solution(below) a and wish to incorporate memoization but don't know if it is possible.

Problem Statement: Given a value N, if we want to make change for N cents, and we have infinite supply of each of S = { S1, S2, .. , Sm} valued coins, Print the number of ways (non-distinct sets) this can be achieved.

Ex: Ex: N = 4 , S = {1, 2, 3}

1 1 1 1 
1 1 2 
1 2 1 
1 3 
2 1 1 
2 2 
3 1 

My code:

public static int change(int n, int count, int sum) {

        if(sum == n) {
            return 1;
        }
        if(sum > n) {
            return 0;
        }
        for(int i = 1; i <=3; i++) {
            sum = sum + i;
            count += change(n, 0, sum);
            sum = sum - i;
        }
        return count;
    }
Spindoctor
  • 131
  • 2

1 Answers1

1

Memoization can be applied to any function. Whether it helps with a given program or not depends on how often the function is called with the same parameters.

You don't specify what your recursive solution is. Typically for this problem is imagine something like

change(total, denominations) = sum of change(total - k m, denominations \ m) where m = max(denominations) over k m <= total

Can change be called with the same arguments more than once? Yes. For instance if you're trying to make change for $1 you might take two quarters and one dime or you might take no quarters and six dimes. In either case you'll next be asking for the numbers of ways to make forty cents with a dime and a nickel. So you can save something by calculating this once and storing the result.

Daniel McLaury
  • 781
  • 3
  • 9