递归硬币改变c ++

Dar*_*ame 1 c++ recursion coin-change

每次递归调用最小函数时,我的程序似乎都会崩溃.任何人都可以告诉我它崩溃的原因.在我调用最小函数后它会立即冻结.是因为即时通讯使用矢量吗?

#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;
}
Run Code Online (Sandbox Code Playgroud)

Sam*_*hik 5

我试着向你的橡皮鸭解释你的minimum()功能,你的橡皮鸭有一个问题.以下是我们的对话:

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

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

你的橡皮鸭:好的.

    return (minimum(denom,s - 1, N)...
Run Code Online (Sandbox Code Playgroud)

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

:所以,这会产生一个递归调用,具有相同的参数,除了第二个参数递减.第三个参数是N.

你的橡皮鸭:所以,如果第三个参数的值N没有改变,并且递归函数只返回N0或负数时返回而没有递归,并且初始调用minimum()传递一个大于0的值N,那么你什么时候准确递归停止?

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