# All ways to add parenthesis for evaluation

Given a string that represents an expression constituting numbers and binary operator +, – and * only. We need to parenthesize the expression in all possible way and return all evaluated values.

```Input : expr = “3-2-1”
Output : {0, 2}
((3-2)-1) = 0
(3-(2-1)) = 2

Input : expr = "5*4-3*2"
Output : {-10, 10, 14, 10, 34}
(5*(4-(3*2))) = -10
(5*((4-3)*2)) = 10
((5*4)-(3*2)) = 14
((5*(4-3))*2) = 10
(((5*4)-3)*2) = 34
```

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

We can solve this problem by parenthesizing all possible valid substring of the expression and then evaluating them, but as we can see that it will involve solving lots of repeating subproblem, to save ourselves we can follow a dynamic programming approach.
We store the result for each substring in a map and if string in recursion is already solved, we return result from map instead of solving that again.
Below code runs a loop in the string and if at any instant, character is operator then we divide the input from there, recursively solve each part and then combine the result in all possible ways.
See the use of c_str() function, this function converts the C++ string into C char array, this function is used in below code because atoi() function expects a character array as an argument not the string. It converts character array to number.

 `//  C++ program to output all possible values of ` `// an expression by parenthesizing it. ` `#include ` `using` `namespace` `std; ` ` `  `//  method checks, character is operator or not ` `bool` `isOperator(``char` `op) ` `{ ` `    ``return` `(op == ``'+'` `|| op == ``'-'` `|| op == ``'*'``); ` `} ` ` `  `//  Utility recursive method to get all possible ` `// result of input string ` `vector<``int``> possibleResultUtil(string input, ` `            ``map< string, vector<``int``> > memo) ` `{ ` `    ``//  If already calculated, then return from memo ` `    ``if` `(memo.find(input) != memo.end()) ` `        ``return` `memo[input]; ` ` `  `    ``vector<``int``> res; ` `    ``for` `(``int` `i = 0; i < input.size(); i++) ` `    ``{ ` `        ``if` `(isOperator(input[i])) ` `        ``{ ` `            ``// If character is operator then split and ` `            ``// calculate recursively ` `            ``vector<``int``> resPre = ` `              ``possibleResultUtil(input.substr(0, i), memo); ` `            ``vector<``int``> resSuf = ` `              ``possibleResultUtil(input.substr(i + 1), memo); ` ` `  `            ``//  Combine all possible combination ` `            ``for` `(``int` `j = 0; j < resPre.size(); j++) ` `            ``{ ` `                ``for` `(``int` `k = 0; k < resSuf.size(); k++) ` `                ``{ ` `                    ``if` `(input[i] == ``'+'``) ` `                        ``res.push_back(resPre[j] + resSuf[k]); ` `                    ``else` `if` `(input[i] == ``'-'``) ` `                        ``res.push_back(resPre[j] - resSuf[k]); ` `                    ``else` `if` `(input[i] == ``'*'``) ` `                        ``res.push_back(resPre[j] * resSuf[k]); ` `                ``} ` `            ``} ` `        ``} ` `    ``} ` ` `  `    ``// if input contains only number then save that  ` `    ``// into res vector ` `    ``if` `(res.size() == 0) ` `        ``res.push_back(``atoi``(input.c_str())); ` ` `  `    ``// Store in memo so that input string is not  ` `    ``// processed repeatedly ` `    ``memo[input] = res; ` `    ``return` `res; ` `} ` ` `  `//  method to return all possible output  ` `// from input expression ` `vector<``int``> possibleResult(string input) ` `{ ` `    ``map< string, vector<``int``> > memo; ` `    ``return` `possibleResultUtil(input, memo); ` `} ` ` `  `//  Driver code to test above methods ` `int` `main() ` `{ ` `    ``string input = ``"5*4-3*2"``; ` `    ``vector<``int``> res = possibleResult(input); ` ` `  `    ``for` `(``int` `i = 0; i < res.size(); i++) ` `        ``cout << res[i] << ``" "``; ` `    ``return` `0; ` `} `

Output:

```-10 10 14 10 34
```

This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

My Personal Notes arrow_drop_up

Article Tags :
Practice Tags :

3

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.
{"ft_lang_label":"__label__en","ft_lang_prob":0.65339214,"math_prob":0.9602893,"size":4407,"snap":"2019-35-2019-39","text_gpt3_token_len":1186,"char_repetition_ratio":0.12559618,"word_repetition_ratio":0.035897437,"special_character_ratio":0.30020422,"punctuation_ratio":0.10431655,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.99715286,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2019-09-17T08:16:49Z\",\"WARC-Record-ID\":\"<urn:uuid:86a2d42e-8b99-4e16-ac16-b21965d9812d>\",\"Content-Length\":\"103946\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:fc031c82-71ac-4ebc-80e3-cbd26265354a>\",\"WARC-Concurrent-To\":\"<urn:uuid:b83ba1fb-8d81-4fbb-be34-1a49206a3745>\",\"WARC-IP-Address\":\"65.158.47.42\",\"WARC-Target-URI\":\"https://www.geeksforgeeks.org/all-ways-to-add-parenthesis-for-evaluation/\",\"WARC-Payload-Digest\":\"sha1:KM6LTTYQQOQZMNOUJ2CE6HCKP73GZJZO\",\"WARC-Block-Digest\":\"sha1:QXL5URE4RWKMGNEEBDYJXLAABHNZUYID\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2019/CC-MAIN-2019-39/CC-MAIN-2019-39_segments_1568514573065.17_warc_CC-MAIN-20190917081137-20190917103137-00300.warc.gz\"}"}