Different Ways to Add parentheses
Total Accepted: 22360 Total Submissions: 62962 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)-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.
Subscribe to see which companies asked this question
Hide TagsDivide and ConquerHide Similar Problems(M) Unique Binary Search Trees II (h) Basic Calculator (h) Expression Add Operators
Java code:
public class Solution {list<integer> Diffwaystocompute (String input) {list<integer> ret = n EW arraylist<integer> (); for (int i=0;i<input.length (); i++) {int c = Input.charat (i); if (c== ' + ' | | c== '-' | | c== ' * ') {list<integer> leftlist = Diffwaystocompute (input.substring (0,i)); list<integer> rightlist = Diffwaystocompute (input.substring (i+1)); for (int left:leftlist) {for (int right:rightlist) {int t = 0; Switch (c) {case ' + ': t = left + right; Break Case '-': t = left-right; Break Case ' * ': t = left * RIGHT; Break } ret.add (t); } }}} if (Ret.size () ==0) {Ret.add (integer.valueof (input)); } return ret; }}
Leetcode:different Ways to Add parentheses