241. Different Ways to ADD parentheses
- Total accepted:27446
- Total submissions:72350
- Difficulty:medium
Given A string of numbers and operators, return all possible results from computing all the different possible ways to Gro Up numbers and operators. The valid operators + are, - and * .
Example 1
Input: "2-1-1" .
((2-1)-10(2-(1-12
Output:[0, 2]
Example 2
Input:"2*3-4*5"
(2*(3-(4*5))) = - the((2*3)-(4*5)) = - -((2*(3-4))*5) = -Ten(2*((3-4)*5)) = -Ten(((2*3)-4)*5) =Ten
Output:[-34, -14, -10, -10, 10]
Idea: Divide and conquer.
Each recursion is written like this:
1. Find a symbol of the current string to divide, left to retain the character of the string to be able to produce the arithmetic value, right to retain the value of the symbol can be generated by the left.size, and then according to the symbolic operation of the () *right.size () times, to get the current string can produce all the values, Returns the result.
2. The symbol is not found, meaning that the current string is numeric and converted to a numeric value.
Code:
1 classSolution {2 Public:3vector<int> Diffwaystocompute (stringInput) {//returns a vector containing all the values that the current string input can produce4vector<int>Left,right,res;5 for(intI=0; I<input.size (); i++){6 if(input[i]=='+'|| input[i]=='-'|| input[i]=='*'){7Left=diffwaystocompute (Input.substr (0, i));8Right=diffwaystocompute (Input.substr (i+1));9 if(input[i]=='+'){Ten for(Auto lnum:left) { One for(Auto rnum:right) { ARes.push_back (lnum+rnum); - } - } the Continue; - } - if(input[i]=='-'){ - for(Auto lnum:left) { + for(Auto rnum:right) { -Res.push_back (lnum-rnum); + } A } at Continue; - } - if(input[i]=='*'){ - for(Auto lnum:left) { - for(Auto rnum:right) { -Res.push_back (lnum*rnum); in } - } to Continue; + } - } the } * if(!res.size ()) { $ intnum=0;Panax Notoginseng for(intI=0; I<input.size (); i++){ -num*=Ten; thenum+=input[i]-'0'; + } A res.push_back (num); the } + returnRes; - } $};
Leetcode 241. Different Ways to Add parentheses