使用递归的函数未按预期工作

A function that uses recursion isn't working as expected

本文关键字:工作 函数 递归      更新时间:2023-10-16
#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;
}