leetcode 241: Different Ways to Add Parentheses

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]

思路:分治,将exp根据运算符拆分成左右两个子表达式,分别计算,合并;(一个表达式遍历运算符,拆分多次)

注意:input[i]-'0'

注意:结果集不必去重

 1 class Solution {
 2 public:
 3     vector<int> diffWaysToCompute(string input) {
 4         vector<int> ans;
 5         int len = input.length();
 6         int flag=0;
 7         int i;
 8         for(i=0;i<len;i++)
 9         {
10             char c = input[i];
11             if(c=='+'||c=='-'||c=='*')
12             {
13                 flag=1;
14                 vector<int> left = diffWaysToCompute(input.substr(0,i));
15                 vector<int> right = diffWaysToCompute(input.substr(i+1,len-i-1));
16                 for(int j=0;j<left.size();j++)
17                 {
18                     for(int k=0;k<right.size();k++)
19                     {
20                         int tmp=0;
21                         if(c == '+')
22                             tmp = left[j]+right[k];
23                         if(c == '-')
24                             tmp = left[j]-right[k];
25                         if(c == '*')
26                             tmp = left[j]*right[k];
27                         ans.push_back(tmp);
28                     }
29                 }
30             }
31         }
32         if(flag==0)
33         {
34             int tmp=0;
35             for(i=0;i<len;i++)
36             {
37                 tmp = tmp*10 + input[i]-'0';
38             }
39             ans.push_back(tmp);
40         }
41         //vector<int> ans2(ans.begin(),ans.end());
42         return ans;
43     }
44 };
View Code

 附:

1 set<int> s;
2 s.insert(1);
3 set<int> s(v.begin(),v.end());
4 vector<int> v(s.begin(),s.end());
原文地址:https://www.cnblogs.com/jsir2016bky/p/5748311.html