<LeetCode>241. 为运算表达式设计优先级

匿名 (未验证) 提交于 2019-12-03 00:30:01

+-*

输入: "2-1-1" 输出: [0, 2] 解释:  ((2-1)-1) = 0  (2-(1-1)) = 2

输入: "2*3-4*5" 输出: [-34, -14, -10, -10, 10] 解释:  (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

解题思路――

1.按照运算符做分割,然后用分治算法解。

2.边界条件为:如果剩下的的字符串中没有运算符,即剩下的字符串中有且仅有数字。

class Solution { public:     vector<int> diffWaysToCompute(string input) {         vector<int> res;         //边界条件是如果找不到运算符,说明只有         for(int i=0;i<input.size();i++)         {             char c = input[i];             if(c=='+'||c=='-'||c=='*')             {                 auto res1 = diffWaysToCompute(input.substr(0,i));                 auto res2 = diffWaysToCompute(input.substr(i+1));                 for(int r1:res1)                     for(int r2:res2)                     {                         if(c=='+')                             res.push_back(r1+r2);                         if(c=='-')                             res.push_back(r1-r2);                           if(c=='*')                             res.push_back(r1*r2);                                             }             }         }         if(res.empty())             res.push_back(stoi(input));                      return res;     } };


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!