Dynamic Programming - Number of combinations to reach a given target

对着背影说爱祢 提交于 2019-12-13 03:31:35

问题


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.

来源:https://stackoverflow.com/questions/50809180/dynamic-programming-number-of-combinations-to-reach-a-given-target

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!