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 is +,-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]
classSolution { Public: vector<int>Diffwaystocompute (stringInput) { vector<int>Result vector<int>Nums vector<char>OperateintPre=0; for(intI=0; I<input.length (); i++) {if(i==0&&input[0]<' 0 '|| input[0]>' 9 ')returnResultif(input[i]>=' 0 '&&input[i]<=' 9 ') {pre=pre*Ten+input[i]-' 0 ';if(I==input.length ()-1) Nums.push_back (pre); }Else if(input[i]==' + '|| input[i]=='-'|| input[i]==' * ') {Nums.push_back (pre); Pre=0; Operate.push_back (Input[i]); }Else returnResult }intCount=nums.size (); vector<vector<vector<int>>>DP (COUNT, vector<vector<int>>(count)); Result=compute (Nums, operate, DP,0, count-1);returnResult } vector<int>Compute vector<int>&nums, vector<char>&operate, vector<vector<vector<int>>> &DP,intLeftintright) { vector<int>Resultif(Left==right) {Result.push_back (nums[left]);returnResult } for(inti=left+1; i<=right;i++) { vector<int>Leftres,rightres; Leftres= (!dp[left][i-1].empty ())? dp[left][i-1]:compute (nums,operate,dp,left,i-1); Rightres= (!dp[i][right].empty ())? Dp[i][right]:compute (Nums,operate,dp,i,right); for(intj=0; J<leftres.size (); j + +) { for(intk=0; K<rightres.size (); k++) {if(operate[i-1]==' + ') Result.push_back (Leftres[j]+rightres[k]);Else if(operate[i-1]=='-') Result.push_back (Leftres[j]-rightres[k]);ElseResult.push_back (Leftres[j]*rightres[k]); }}} Dp[left][right]=result;returnResult }};
The Stone of his mountain:
#include <vector>using namespace STD;classSolution { Public: vector<int>Diffwaystocompute (stringInput) { vector<int>Ret for(inti =0; I < input.size (); i++) {if(Input[i] = =' + '|| Input[i] = ='-'|| Input[i] = =' * ') { vector<int>left = Diffwaystocompute (Input.substr (0, i)); vector<int>right = Diffwaystocompute (Input.substr (i +1)); for(intj =0; J < Left.size (); J + +) { for(intK =0; K < Right.size (); k++) {if(Input[i] = =' + ') Ret.push_back (Left[j] + right[k]);Else if(Input[i] = ='-') Ret.push_back (Left[j]-right[k]);ElseRet.push_back (left[j] * right[k]); } } } }if(Ret.empty ()) Ret.push_back (Atoi (Input.c_str ()));returnRet }};
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode 241-different Ways to ADD parentheses