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

时间:2017-07-06 16:26:56

标签: c++ c++11

#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个整数和一个目标号码。该程序应该返回您必须执行的操作才能达到目标编号。

示例输入:

7 3 100 7 25 9
881

示例输出:

*+*++

输入的另一个例子:

100 6 3 75 50 25
952

输出:

+**-/

输入的另一个例子:

3 8 7 6 3 1
250

以上示例的输出示例:

+*+*+

请注意,此程序的操作从左到右,即

(((((3+8)*7)+6)*3)+1) = 250

这是我在reddit上发现的挑战的解决方案。我想用递归来解决这个问题。我试过了,但它似乎没有正常工作。几个星期以来,我一直在解决这个问题。

谢谢你,祝你有愉快的一天。

1 个答案:

答案 0 :(得分:0)

确保每条路径都有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;
}