递归换币c++
Recursive coin change c++
每次递归调用最小函数时,我的程序似乎都会崩溃。有人能告诉我它为什么会坠毁吗。在我调用最小函数后,它会立即冻结。是因为我用了一个向量吗?
#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/
相关文章:
- 通过递归进行因子分解
- 递归函数计算序列中的平方和(并输出过程)
- 使用递归的数组的最小值.这是怎么回事
- 递归列出所有目录中的C++与Python与Ruby的性能
- 递归计数给定目录的文件和所有目录
- 如何在BST的这个简单递归实现中消除警告
- C++:正在检查LinkedList中的回文-递归方法-错误
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 递归无序映射
- TSP递归解的迭代形式
- 如何在Elixir中调用递归函数并行
- 返回递归调用和仅递归调用的区别
- 数组元素打印的递归方法
- 使用递归时获取变量的奇怪值
- 如何在C++中递归地按相反顺序打印集合
- 到连接组件算法的问题(递归)
- 如何使用递归打印修改后的星号三角形图案
- 使用递归模板动态分配的多维数组
- 递归函数有效,但无法记忆
- 包含模板文件的递归会导致编译失败