【算法】【Divide and conquer】Different Ways to Add Parentheses

来源:互联网 发布:sql联合主键查询 编辑:程序博客网 时间:2024/06/04 01:19

Difficulty:Medium

Description

Given a string of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid operators are +, - and *.

Example 1

Input: "2-1-1".

((2-1)-1) = 0
(2-(1-1)) = 2

Output: [0, 2]

Example 2

Input: "2*3-4*5"

(2*(3-(4*5))) = -34
((2*3)-(4*5)) = -14
((2*(3-4))*5) = -10
(2*((3-4)*5)) = -10
(((2*3)-4)*5) = 10

Output: [-34, -14, -10, -10, 10]

Solution

我的思路

采用Divide-and-conquer的思想,将一个算式以运算符为分割处,分割成若干个算式。由于算式中可能有多个运算符,因此可以在不同地方进行分割,因而计算出不同的结果(返回一个数组,该数组包含所有的运算结果)。若算式中没有运算符,则该算式为一个整数,该整数就是一个结果(返回一个数组,该数组只包含一个整数)。

将该思路转为代码,就是调用递归函数,不断将算式分割,计算出每一部分的子算式结果,再返回。

代码

class Solution {public:    // 这是入口,相当于主函数    vector<int> diffWaysToCompute(string input) {        vector<int> output = calculate(input);   // 调用递归函数        return output;    }    vector<int> calculate(string input) {        string input1 = "", input2 = "";        vector<int> opPos;       // 存储运算符所在字符串的位置        vector<int> outputList;    // 该函数的返回结果,返回输入的算式的所有结果        for (int i = 0; i < input.length(); ++i) {            if (input[i] == '+' || input[i] == '-' || input[i] == '*') {                opPos.insert(opPos.begin(), i);            }        }        if (opPos.size() == 0) {                    // 若该字符串没有运算符,直接转化为int            stringstream ss;            int output;            ss << input;            ss >> output;            outputList.push_back(output);            return outputList;        }        else {                                   // 若该字符串有多个运算符            int pos, num1, num2;            for (int i = 0; i < opPos.size(); ++i)            {                pos = opPos[i];                input1.append(input, 0, pos);            // input1存入运算符前面的字符串                input2.append(input, pos + 1, input.length() - pos);  // input2存入运算符后面的字符串                vector<int> operands1, operands2;     // 分别存储input1和input2算式计算出的所有结果                operands1 = calculate(input1);                operands2 = calculate(input2);                if (input[pos] == '*') {                    for (auto num1 : operands1) {                        for (auto num2 : operands2) {                            outputList.push_back(num1 * num2);                        }                    }                }                else if (input[pos] == '+') {                    for (auto num1 : operands1) {                        for (auto num2 : operands2) {                            outputList.push_back(num1 + num2);                        }                    }                }                else {                    for (auto num1 : operands1) {                        for (auto num2 : operands2) {                            outputList.push_back(num1 - num2);                        }                    }                }input2 = "";            }            return outputList;        }    }};
阅读全文
0 0