Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
102 views
in Technique[技术] by (71.8m points)

c++ - Dynamic programming doesn't retrieve all the values that I expect

Here's the problem that I'm trying to solve:

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, how many ways can we make the change? The order of coins doesn’t matter.

For example, for N = 4 and S = {1,2,3}, there are four solutions: {1,1,1,1}, {1,1,2}, {2,2}, {1,3}.

So output should be 4. For N = 10 and S = {2, 5, 3, 6}, there are five solutions: {2,2,2,2,2}, {2,2,3,3}, {2,2,6}, {2,3,5} and {5,5}. So the output should be 5.

Here's my solution:

#include <iostream>
#include <vector>
#include <optional>

std::optional<std::vector<int>> findCoins(int n, int array[], int nrCoins)
{
    if (n == 0) return std::vector<int>();
    if (n < 0) return std::nullopt;

    for (int i = 0; i < nrCoins; i++)
    {
        int x = n - array[i];
        std::optional<std::vector<int>> xRes = findCoins(x, array, nrCoins);
        if (xRes != std::nullopt)
        {
            xRes->push_back(array[i]);
            return xRes;
        }
    }
    return std::nullopt;
}

int main()
{
    int vector[3]{ 1, 2, 3 };
    int nr = 0;
    std::vector<int> coinuri = findCoins(4, vector, 3).value();
    for (int num : coinuri)
    {
        std::cout << num << " ";
    }
    return 0;
}

For that example, the recursion tree looks like this:

photo

it's not the best picture

But, instead of getting 7 results from my program (because in the tree there are 7 leafs with value = 0), I only get 1 result, and that one is the most left-sided one.

I think that in order to get 7 results instead of 1, I should use a matrix and store each result - that's why my program only returns 1. But, how can I do that using std::vector?

question from:https://stackoverflow.com/questions/65906994/dynamic-programming-doesnt-retrieve-all-the-values-that-i-expect

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...