Dynamic Programming - Number of combinations to re

2019-08-25 03:22发布

问题:

This is a basic dynamic programming problem - Number of score combinations. I am aware of the bottom up approach for this problem which works well.

However, I am unable to work towards finding a top-down solution approach for the problem. Caching the recursive part gives us more than necessary combinations(where ordering/sequence of scores is also a factor, so, to avoid it we need to provide a constraint to make the sequence increase monotonically. Here is recursive approach for the same. Dynamic Programming - Number of distinct combinations to reach a given score

Here is my current code:

#include <iostream>
#include <vector>
using namespace std;

int helper(int target, vector<int>& coins, vector<int>& cache, int min) {
    if(target < 0) return 0;
    if(target == 0) return 1;
    if(cache[target] != 0) return cache[target];

    for(auto& c : coins) {
        if(target >= c && min <= c) {
            //cout << min << " " << c << " " << target << endl;
            cache[target] += helper(target-c, coins, cache, c) ;
            //cout << cache[target] << endl;            
        }

    }

    return cache[target];

}


int main() {

    vector<int> coins{2, 3};

    int target = 7;
    vector<int> cache(target+1, 0);
    cache[0] = 1;
    cache [7] = helper(target, coins, cache, 1);

    for (auto& x : cache) cout << x << endl;
    return 0;
}

Here is run-able ideone link.