Different Ways to Add parenthesesTotal accepted:1708 Total submissions:6304my submissions QuestionSolution
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)-1) = 0 ((1-1)) = 2
Output:[0, 2]
Example 2
Input:"2*3-4*5"
((4*5)) =-34 ((2*3)-(4*5)) = 14 ((3-4)) = 10 (((3-4))) =-10 (((2*3) 4) = 10
Output:[-34, -14, -10, -10, 10]
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
Hide TagsDivide and ConquerHide Similar Problems(M) Basic CalculatorReference the
C + + 4ms Recursive & DP Solution with brief Explanation-leetcode discuss
Https://leetcode.com/discuss/48488/c-4ms-recursive-method
This topic means that you can calculate the possible results for a string of strings in parentheses.
1. Beginning not understand, in fact, this problem is calculated under different brackets under the results of the situation, and the final real calculation is to be able to
The result of the repetition.
The first is the idea of the basic recursion, the previous traversal, for each operator to divide its left and right substrings into two parts, and then calculate the different results on both sides, and then together, there is no parentheses in the same hair situation.
1#include <iostream>2#include <vector>3 using namespacestd;4 5vector<int> Diffwaystocompute (stringinput) {6vector<int>result;7 intlen=input.size ();8 for(intk=0; k<len;k++)9 {Ten if(input[k]=='+'|| input[k]=='-'|| input[k]=='*') One { Avector<int> Result1=diffwaystocompute (INPUT.SUBSTR (0, k)); -vector<int> Result2=diffwaystocompute (input.substr (k +1)); - for(vector<int>::iterator I=result1.begin (); I!=result1.end (); i++) the for(vector<int>::iterator J=result2.begin (); J!=result2.end (); j + +) - { - if(input[k]=='+') -Result.push_back ((*i) + (*j)); + Else if(input[k]=='-') -Result.push_back ((*i)-(*j)); + Else AResult.push_back ((*i) * (*j)); at } - } - } - if(Result.empty ()) - Result.push_back (Atoi (Input.c_str ())); - returnresult; in } - intMain () to { + stringinput="2*3-4*5"; -vector<int>Vec; theVec=Diffwaystocompute (input); * for(intI=0; I<vec.size (); i++) $cout<<vec[i]<<' ';Panax Notoginsengcout<<Endl; -System"Pause"); the}
Leetcode_241--different Ways to Add parentheses (recursive, dynamic planning)