Different Ways to Add parentheses
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]
The first thing that came to mind when this topic was started was the idea that all the parentheses were generated, that is, all expression was generated, and then the method of evaluating the expression was used to obtain the result.
Later found that the topic of the hint using a divide-and-conquer algorithm, omg!!
First, the input string is decomposed into two parts
Data and operator
Like 2*3-4*5.
Data:2 | 3 | 4 | 5
operator:* | - | *
We can constantly choose mid-mid to divide data into two parts, here mid=[0,1,2]
The last number that represents the left part of the division, and the beginning of the corresponding right part is from [three-to-one]
In fact, the idea has been very clear, directly paste the code
1 ImportJava.util.*;2 3 Public classSolution {4 PrivateList<integer> Divide (vector<character> op, vector<integer> data,intDStart,intdend) {5 if(dstart==dend) {6list<integer> res =NewLinkedlist<integer>();7 Res.add (Data.get (DStart));8 returnRes;9 }Tenlist<integer> res =NewLinkedlist<integer>(); One for(intMID = dstart;mid<dend;mid++){ AList<integer> left =divide (op,data,dstart,mid); -List<integer> right = Divide (op,data,mid+1, dend); - CharOPC =Op.get (mid); the for(intI=0;i<left.size (); i++){ - for(intJ=0;j<right.size (); j + +){ - intTMP = 0; - Switch(OPC) { + Case+: -TMP = Left.get (i) +Right.get (j); + Break; A Case‘-‘: atTMP = Left.get (i)-Right.get (j); - Break; - Case‘*‘: -TMP = Left.get (i) *Right.get (j); - Break; - } in Res.add (TMP); - } to } + } - returnRes; the } * PublicList<integer>diffwaystocompute (String input) { $Vector<character> op =NewVector<character>();Panax Notoginsengvector<integer> data =NewVector<integer>(); - intindex = 0; the while(index<input.length ()) { + Charc =Input.charat (index); A if(c== ' + ' | | c== '-' | | c== ' * '){ the Op.add (c); +index++; -}Else{ $ intEndindex = index+1; $ while(Endindex<input.length () &&character.isdigit (Input.charat (endindex))) endindex++; -String tmp =input.substring (index,endindex); - Data.add (Integer.parseint (TMP)); theindex =Endindex; - }Wuyi } the returnDivide (Op,data,0,data.size ()-1); - } Wu}
[Leetcode] Different Ways to Add parentheses