Leetcode 241. Different Ways to Add Parentheses

来源:互联网 发布:帝国cms好用吗 编辑:程序博客网 时间:2024/06/10 02:47

题目描述:
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]

题目分析:
这是一道分治算法的题目,要算出所有不同优先顺序下算式的结果,那么根据分治算法的思想,将问题转化为子问题求解,则应该在遇到一个运算符后将前后两部分算式分别递归求结果,然后再合并,得到最终的算式结果。

具体步骤:

  • step1:遍历整个字符串,遇到运算符后,以运算符为分界,对前后两个子串分别递归求运算结果。
  • step2:分治结束后,对得到的两个子串的各个不同的运算结果一一对应进行合并。
  • step3:如果没有运算符,说明只有一个数字,则将其放入数组中返回即可。

代码:

#include <iostream>#include <string>#include <sstream>#include <vector>using namespace std;class Solution {public:    vector<int> diffWaysToCompute(string input) {        vector<int> res;        for (int i = 0; i < input.size(); i++){            if (input[i] == '+' || input[i] == '-' || input[i] == '*'){                /*对前后两个子串分别递归求运算结果*/                 vector<int> res1 = diffWaysToCompute(input.substr(0, i));                vector<int> res2 = diffWaysToCompute(input.substr(i + 1));                /*对两个子串各个不同的运算结果一一对应进行合并*/                 for (int j = 0; j < res1.size(); j++){                    for (int k = 0; k < res2.size(); k++){                        if (input[i] == '+'){                            res.push_back(res1[j] + res2[k]);                        }                        else if (input[i] == '-'){                            res.push_back(res1[j] - res2[k]);                        }                        else{                            res.push_back(res1[j] * res2[k]);                        }                    }                }            }        }        /*如果没有运算符,说明只有一个数字,则将其放入数组中返回即可*/         if (res.empty()){            int temp;            stringstream ss;            ss << input;            ss >> temp;            res.push_back(temp);        }        return res;    }};