📜  查找给定表达式的所有可能结果

📅  最后修改于: 2021-05-04 09:55:49             🧑  作者: Mango

给定一个算术表达式,找到该表达式的所有可能结果。通过将括号放在不同的位置来评估不同的结果。

我们可以假设数字是给定表达式中的一位数字。

例子:

Input:  1+3*2
Output: 8  7
Explanation
(1 + 3)*2     = 80
(1 + (3 * 2)) = 70

Input:  1*2+3*4
Output: 14 20 14 20 20
 (1*(2+(3*4))) =  14
 (1*((2+3)*4)) =  20 
 ((1*2)+(3*4)) =  14
 ((1*(2+3))*4) =  20
 ((1*2)+3)*4)  =  20

想法是遍历给定表达式中的每个运算符。对于每个运算符,请评估其左侧和右侧的所有可能值。在每对左侧和右侧值上应用当前运算符,然后将所有评估值添加到结果中。

1) Initialize result 'res' as empty.
2) Do following for every operator 'x'.
    a) Recursively evaluate all possible values on left of 'x'.
       Let the list of values be 'l'.  
    a) Recursively evaluate all possible values on right of 'x'.
       Let the list of values be 'r'.
    c) Loop through all values in list 'l'  
           loop through all values in list 'r'
               Apply current operator 'x' on current items of 
               'l' and 'r' and add the evaluated value to 'res'   
3) Return 'res'.

下面是上述算法的实现。

C++
// C++ program to evaluate all possible values of
// a expression
#include
using namespace std;
  
// Utility function to evaluate a simple expression
// with one operator only.
int eval(int a, char op, int b)
{
    if (op=='+')   return a+b;
    if (op=='-')   return a-b;
    if (op == '*') return a*b;
}
  
// This function evaluates all possible values and
// returns a list of evaluated values.
vector evaluateAll(string expr, int low, int high)
{
    // To store result (all possible evaluations of
    // given expression 'expr')
    vector res;
  
    // If there is only one character, it must
    // be a digit (or operand), return it.
    if (low == high)
    {
        res.push_back(expr[low] - '0');
        return res;
    }
  
    // If there are only three characters, middle
    // one must be operator and corner ones must be
    // operand
    if (low == (high-2))
    {
        int num = eval(expr[low]-'0', expr[low+1],
                       expr[low+2]-'0');
  
        res.push_back(num);
        return res;
    }
  
    // every i refers to an operator
    for (int i=low+1; i<=high; i+=2)
    {
        // l refers to all the possible values
        // in the left of operator 'expr[i]'
        vector l = evaluateAll(expr, low, i-1);
  
        // r refers to all the possible values
        // in the right of operator 'expr[i]'
        vector r = evaluateAll(expr, i+1, high);
  
        // Take above evaluated all possible
        // values in left side of 'i'
        for (int s1=0; s1 ans = evaluateAll(expr, 0, len-1);
  
    for (int i=0; i< ans.size(); i++)
        cout << ans[i] << endl;
  
    return 0;
}


Java
// Java program to evaluate all possible 
// values of a expression
import java.util.*;
  
class GFG 
{
  
    // Utility function to evaluate a simple expression
    // with one operator only.
    static int eval(int a, char op, int b) 
    {
        if (op == '+')
        {
            return a + b;
        }
        if (op == '-')
        {
            return a - b;
        }
        if (op == '*') 
        {
            return a * b;
        }
        return Integer.MAX_VALUE;
    }
  
    // This function evaluates all possible values and
    // returns a list of evaluated values.
    static Vector evaluateAll(String expr,
                                    int low, int high) 
    {
        // To store result (all possible evaluations of
        // given expression 'expr')
        Vector res = new Vector();
  
        // If there is only one character, it must
        // be a digit (or operand), return it.
        if (low == high) 
        {
            res.add(expr.charAt(low) - '0');
            return res;
        }
  
        // If there are only three characters, middle
        // one must be operator and corner ones must be
        // operand
        if (low == (high - 2)) 
        {
            int num = eval(expr.charAt(low) - '0', 
                         expr.charAt(low + 1),
                        expr.charAt(low + 2) - '0');
  
            res.add(num);
            return res;
        }
  
        // every i refers to an operator
        for (int i = low + 1; i <= high; i += 2) 
        {
              
            // l refers to all the possible values
            // in the left of operator 'expr[i]'
            Vector l = evaluateAll(expr, low, i - 1);
  
            // r refers to all the possible values
            // in the right of operator 'expr[i]'
            Vector r = evaluateAll(expr, i + 1, high);
  
            // Take above evaluated all possible
            // values in left side of 'i'
            for (int s1 = 0; s1 < l.size(); s1++) 
            {
                  
                // Take above evaluated all possible
                // values in right side of 'i'
                for (int s2 = 0; s2 < r.size(); s2++) 
                {
                      
                    // Calculate value for every pair
                    // and add the value to result.
                    int val = eval(l.get(s1), expr.charAt(i), r.get(s2));
                    res.add(val);
                }
            }
        }
        return res;
    }
  
    // Driver program
    public static void main(String[] args) 
    {
        String expr = "1*2+3*4";
        int len = expr.length();
        Vector ans = evaluateAll(expr, 0, len - 1);
  
        for (int i = 0; i < ans.size(); i++) 
        {
            System.out.println(ans.get(i));
        }
    }
}
  
// This code has been contributed by 29AjayKumar


Python3
# Python3 program to evaluate all 
# possible values of a expression 
  
# Utility function to evaluate a simple 
# expression with one operator only. 
def eval(a, op, b): 
  
    if op == '+': return a + b 
    if op == '-': return a - b 
    if op == '*': return a * b 
  
# This function evaluates all possible values 
# and returns a list of evaluated values. 
def evaluateAll(expr, low, high): 
  
    # To store result (all possible 
    # evaluations of given expression 'expr') 
    res = [] 
  
    # If there is only one character, 
    # it must be a digit (or operand), 
    # return it. 
    if low == high: 
      
        res.append(int(expr[low])) 
        return res 
  
    # If there are only three characters, 
    # middle one must be operator and  
    # corner ones must be operand 
    if low == (high - 2): 
      
        num = eval(int(expr[low]), 
                       expr[low + 1], 
                   int(expr[low + 2])) 
  
        res.append(num) 
        return res 
  
    # every i refers to an operator 
    for i in range(low + 1, high + 1, 2): 
      
        # l refers to all the possible values 
        # in the left of operator 'expr[i]' 
        l = evaluateAll(expr, low, i - 1) 
  
        # r refers to all the possible values 
        # in the right of operator 'expr[i]' 
        r = evaluateAll(expr, i + 1, high) 
  
        # Take above evaluated all possible 
        # values in left side of 'i' 
        for s1 in range(0, len(l)): 
          
            # Take above evaluated all possible 
            # values in right side of 'i' 
            for s2 in range(0, len(r)): 
              
                # Calculate value for every pair 
                # and add the value to result. 
                val = eval(l[s1], expr[i], r[s2]) 
                res.append(val) 
      
    return res 
  
# Driver Code
if __name__ == "__main__": 
  
    expr = "1*2+3*4"
    length = len(expr) 
    ans = evaluateAll(expr, 0, length - 1) 
  
    for i in range(0, len(ans)):
        print(ans[i])
  
# This code is contributed by Rituraj Jain


C#
// C# program to evaluate all possible 
// values of a expression
using System;
using System.Collections.Generic;
  
class GFG 
{
  
    // Utility function to evaluate a simple expression
    // with one operator only.
    static int eval(int a, char op, int b) 
    {
        if (op == '+')
        {
            return a + b;
        }
        if (op == '-')
        {
            return a - b;
        }
        if (op == '*') 
        {
            return a * b;
        }
        return int.MaxValue;
    }
  
    // This function evaluates all possible values and
    // returns a list of evaluated values.
    static List evaluateAll(String expr,
                                    int low, int high) 
    {
        // To store result (all possible evaluations of
        // given expression 'expr')
        List res = new List ();
  
        // If there is only one character, it must
        // be a digit (or operand), return it.
        if (low == high) 
        {
            res.Add(expr[low] - '0');
            return res;
        }
  
        // If there are only three characters, middle
        // one must be operator and corner ones must be
        // operand
        if (low == (high - 2)) 
        {
            int num = eval(expr[low] - '0', 
                        expr[low + 1],
                        expr[low + 2] - '0');
  
            res.Add(num);
            return res;
        }
  
        // every i refers to an operator
        for (int i = low + 1; i <= high; i += 2) 
        {
              
            // l refers to all the possible values
            // in the left of operator 'expr[i]'
            List l = evaluateAll(expr, low, i - 1);
  
            // r refers to all the possible values
            // in the right of operator 'expr[i]'
            List r = evaluateAll(expr, i + 1, high);
  
            // Take above evaluated all possible
            // values in left side of 'i'
            for (int s1 = 0; s1 < l.Count; s1++) 
            {
                  
                // Take above evaluated all possible
                // values in right side of 'i'
                for (int s2 = 0; s2 < r.Count; s2++) 
                {
                      
                    // Calculate value for every pair
                    // and add the value to result.
                    int val = eval(l[s1], expr[i], r[s2]);
                    res.Add(val);
                }
            }
        }
        return res;
    }
  
    // Driver code
    public static void Main() 
    {
        String expr = "1*2+3*4";
        int len = expr.Length;
        List ans = evaluateAll(expr, 0, len - 1);
  
        for (int i = 0; i < ans.Count; i++) 
        {
            Console.WriteLine(ans[i]);
        }
    }
}
  
/* This code contributed by PrinciRaj1992 */


PHP


输出:

14
20
14
20
20

练习:扩展上述解决方案,使其也适用于具有多个数字的数字。例如,“ 100 * 30 + 20”之类的表达式(提示:我们可以创建一个整数数组来存储给定表达式的所有操作数和运算符)。