使用递归的函数未按预期工作
A function that uses recursion isn't working as expected
#include <iostream>
#include <vector>
using namespace std;
const int maxx = 6;
vector <int> nums {maxx};
string ops = "-----";
bool fillOps (int target, int n=maxx-1) {
if (n == 0) {
if (nums[n]==target) {
cout << target << " GOOD " << endl;
return true;
} else {
cout << target << " GOOD " << endl;
return false;
}
}
if (nums[n] != 0) {
if (fillOps(target/nums[n], n-1)) {
ops[n-1]='*';
return true;
}
} else if (fillOps(target*nums[n], n-1)) {
ops[n-1]='/';
return true;
} else if (fillOps(target+nums[n], n-1)) {
ops[n-1]='-';
return true;
} else if (fillOps(target-nums[n], n-1)) {
ops[n-1]='+';
return true;
} else
return false;
}
int main() {
ops=".....";
for (int i=0; i<maxx; i++)
cin >> nums[i];
int target;
cin >> target;
if (fillOps(target))
cout << ops;
else
cout << "No solution exists.";
}
用户应输入 5 个整数和一个目标数字。该程序应该返回您必须执行的操作才能获得目标数字。
示例输入:
73 100 7 25 9
881
示例输出:
*+*++
另一个输入示例:
100 6 3 75 50 25
952
其输出:
+**-/
另一个输入示例:
38 7 6 3 1
250
上述示例的输出示例:
+*+*+
请注意,该程序的操作从左到右,即
(((((3+8)*7)+6)*3)+1) = 250
这是我在reddit上发现的挑战的解决方案。我想使用递归来解决这个问题。我试过了,但它似乎无法正常工作。几个星期以来,我一直在为这个问题而苦恼。
谢谢你,祝你有美好的一天。
确保每个路径都有一个return
。不要以相反的顺序计算,这会使算法复杂化。请参阅我的以下代码并阅读注释:
const int maxx = 5;
std::vector <int> nums(maxx); // <-- vector with 5 elements
std::string ops = "-----";
bool fillOps (int target, int current, int n=maxx-1) {
if (n == 0) {
// end of recursion path : do no output here becaus it is too early
return current == target;
}
int i = maxx - n;
if (nums[i] != 0 && // <-- test divison by zero
target % nums[n] == 0 && // <-- test division has no rest
fillOps(target, current/nums[i], n-1) ) { // <-- and fillOps in same condition
ops[i-1]='/';
return true;
} else if (fillOps(target, current*nums[i], n-1)) {
ops[i-1]='*';
return true;
} else if (fillOps(target, current-nums[i], n-1)) {
ops[i-1]='-';
return true;
} else if (fillOps(target, current+nums[i], n-1)) {
ops[i-1]='+';
return true;
}
return false;
}
int main() {
ops=".....";
for (int i=0; i<maxx; i++)
std::cin >> nums[i];
int target;
std::cin >> target;
if (fillOps(target, nums[0]))
std::cout << ops;
else
std::cout << "No solution exists.";
return 0;
}
相关文章:
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- C++中的memset函数工作不正常
- 将返回值存储在函数指针数组的指针中是如何工作的?
- insertElement() 函数无法按预期工作
- 即使没有调用这个递归函数,它是如何工作的?
- type_info成员函数如何工作?
- 如何定义在用作函数参数时工作的类模板的转换
- 优先级队列构造函数的工作
- 有人可以解释一下这个矩阵幂函数是如何工作的吗?
- 使用移动和复制语义时函数匹配如何工作?
- 这个C++编译器优化(在自身的实例上调用对象自己的构造函数)的名称是什么,它是如何工作的?
- C++代码停止工作错误使用cout内部函数
- 好友函数的工作原理
- 为什么 sizeof(ar)/ sizeof(ar[0]) 在传递给函数时无法在向量上正常工作?
- 以下代码如何工作以每次为唯一调用堆栈唯一实例化模板函数?
- 递归函数调用在后台工作
- 如何使函数在派生类中工作?
- 在下面的代码中,虚函数是如何工作的
- 工作函数重载如何使用可变参数解析?
- C++继承和具有虚拟工作函数的Pthreads