递归换币c++

Recursive coin change c++

本文关键字:c++ 递归      更新时间:2023-10-16

每次递归调用最小函数时,我的程序似乎都会崩溃。有人能告诉我它为什么会坠毁吗。在我调用最小函数后,它会立即冻结。是因为我用了一个向量吗?

#include <iostream>
#include <vector>
#include <math.h>
#include <algorithm>
using namespace std;
int minimum(vector<int> denom, int s, int N) //take in denomination , sizeofcoin, and value of N
{
    if(N == 0)
    {
        return 1;
    }
    else if(N < 0 || (N > 0 && s <=0))
    {
        return 0;
    }
    else
    {
        return min(minimum(denom,s - 1, N), 1 + minimum(denom, s,N-denom[s-1]));
    }
}
int main()
{
    int N;
    unsigned int sizeofcoin;
    cout << "Enter the value N to produce: " << endl;
    cin >> N;
    cout << "Enter the number of different denominations: " << endl;
    cin >> sizeofcoin;
    vector<int> denom(sizeofcoin);
    for(unsigned int i= 0; i < sizeofcoin; i++)
    {
        cout << "Enter denomination #" << (i+1) << endl;          //save all the denominations in an array
        cin >> denom[i];
    }
    sort(denom.begin() , denom.end(),greater<int>());    //sort the array from largest to smallest
    if(denom.back() != 1)                                 //check the end of the array (since the back is smallest now) if it has 1
    {
        denom.push_back(1);                             //Will include 1 if the user does not input a 1 (doesn't have to be used)
    }
    minimum(denom,sizeofcoin,N);
    return 0;
}

我试图向您的橡皮鸭解释您的minimum()函数,但您的橡皮鸭子有一个问题要问。以下是我们的对话:

int minimum(vector<int> denom, int s, int N) //take in denomination , sizeofcoin, and value of N
{
    if(N <= 0)
    {
        return 0;
    }

Me:如果minimum()递归函数的第三个参数N为0或负数,则该函数立即返回。

你的橡皮鸭:好的。

    return (minimum(denom,s - 1, N)...

(在这里,我试着向你的橡皮鸭解释你的第一个递归调用):

Me:因此,这将使用相同的参数进行递归调用,只是第二个参数递减。第三个参数是N

Your Rubber Duck:那么,如果第三个参数的值N不变,并且递归函数只有在N为0或负时才返回而不递归,并且对minimum()的初始调用为N传递了一个大于0的值,那么您希望此递归何时停止?

我自己无法回答这个问题,也许你可以自己向你的橡皮鸭解释。递归什么时候停止?

您有递归调用minimum(denom,s - 1, N),因此N永远不会小于或等于0,并且递归永远不会结束。

如果您学会了如何使用调试器,并且逐行地执行代码,并逐步执行递归调用,那么这将非常容易找到。

我想指出的另一件事是,您试图返回两个值的总和:

(minimum(denom,s - 1, N) + minimum(denom, s,N-denom[s-1])

相反,你应该做的是:

min(minimum(denom,s - 1, N), 1 + minimum(denom, s,N-denom[s-1]))

这个想法是,在第一次通话中,你没有使用任何硬币,但在第二次通话中你使用了一枚,所以加1表示相同。

寻找同样的动态编程解决方案。https://people.cs.clemson.edu/~bcdean/dp_practice/