📜  打印所有求值到目标的可能表达式

📅  最后修改于: 2021-04-29 13:26:34             🧑  作者: Mango

给定一个仅包含0到9的数字和整数值target的字符串。找出在给定的数字字符串中使用二元运算符+,–和*求值的目标可能有多少个表达式。

Input : "123",  Target : 6
Output : {“1+2+3”, “1*2*3”}

Input : “125”, Target : 7
Output : {“1*2+5”, “12-5”}

通过将所有可能的二进制运算符放在数字中间并对其进行评估,然后检查其评估结果是否为目标,可以解决此问题。

  • 在编写递归代码时,我们需要将这些变量保留为递归方法的参数-结果向量,输入字符串,当前表达式字符串,目标值,处理输入的位置,当前求值和求值中的最后一个值。
  • 由于乘法运算,最后值保持递归,而在进行乘法运算时,我们需要最后一个值以进行正确求值。

请参阅以下示例,以更好地理解–

Input is 125, suppose we have reached till 1+2 now,
Input = “125”, current expression = “1+2”, 
position = 2, current val = 3, last = 2

Now when we go for multiplication, we need last 
value for evaluation as follows:

current val = current val - last + last * current val

First we subtract last and then add last * current 
val for evaluation, new last is last * current val.
current val = 3 – 2 + 2*5 = 11
last = 2*5 = 10 

在下面的代码中要注意的另一件事是,我们忽略了所有从0开始的数字,方法是将一个条件作为第一个条件强加到循环中,这样我们就不会处理03、05等数字。

请参见c_str()函数的使用,此函数将C++字符串转换为C char数组,此函数在以下代码中使用,因为atoi()函数期望将字符数组作为参数而不是字符串。它将字符数组转换为数字。

// C++ program to find all possible expression which
// evaluate to target
#include 
using namespace std;
  
// Utility recursive method to generate all possible
// expressions
void getExprUtil(vector& res, string curExp,
                 string input, int target, int pos,
                 int curVal, int last)
{
    // true if whole input is processed with some
    // operators
    if (pos == input.length())
    {
        // if current value is equal to target
        //then only add to final solution
        // if question is : all possible o/p then just
        //push_back without condition
        if (curVal == target)
            res.push_back(curExp);
        return;
    }
  
    // loop to put operator at all positions
    for (int i = pos; i < input.length(); i++)
    {
        // ignoring case which start with 0 as they
        // are useless for evaluation
        if (i != pos && input[pos] == '0')
            break;
  
        // take part of input from pos to i
        string part = input.substr(pos, i + 1 - pos);
  
        // take numeric value of part
        int cur = atoi(part.c_str());
  
        // if pos is 0 then just send numeric value
        // for next recurion
        if (pos == 0)
            getExprUtil(res, curExp + part, input,
                     target, i + 1, cur, cur);
  
  
        // try all given binary operator for evaluation
        else
        {
            getExprUtil(res, curExp + "+" + part, input,
                     target, i + 1, curVal + cur, cur);
            getExprUtil(res, curExp + "-" + part, input,
                     target, i + 1, curVal - cur, -cur);
            getExprUtil(res, curExp + "*" + part, input,
                     target, i + 1, curVal - last + last * cur,
                     last * cur);
        }
    }
}
  
// Below method returns all possible expression
// evaluating to target
vector getExprs(string input, int target)
{
    vector res;
    getExprUtil(res, "", input, target, 0, 0, 0);
    return res;
}
  
// method to print result
void printResult(vector res)
{
    for (int i = 0; i < res.size(); i++)
        cout << res[i] << " ";
    cout << endl;
}
  
// Driver code to test above methods
int main()
{
    string input = "123";
    int target = 6;
    vector res = getExprs(input, target);
    printResult(res);
  
    input = "125";
    target = 7;
    res = getExprs(input, target);
    printResult(res);
    return 0;
}

输出:

1+2+3 1*2*3 
1*2+5 12-5