Different Ways to Add Parentheses

Given a string expression of numbers and the operators +, - and *, return every result you can get by grouping the numbers and operators in all possible ways with parentheses. The answer may be returned in any order.

30:00

Different Ways to Add Parentheses
medium
Free written solution
Topics
Companies

Given a string expression of numbers and the operators +, - and *, return every result you can get by grouping the numbers and operators in all possible ways with parentheses. The answer may be returned in any order.

Example 1:
Input: {"expression":"2-1-1"}
Output: [2,0]
Constraints:
  • 1≤expression.length≤201 \leq \text{expression.length} \leq 20

  • expression consists of digits and the operators +, - and *.

  • All integer values in the input expression are in the range [0,99][0, 99].

  • The integer values in the input expression do not have a leading - or +.

  • The number of different results does not exceed 10410^4, and every result fits in a 32-bit integer.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"expression":"2-1-1"}
2

last

-

last

1

last

-

last

1

last

Expression "2-1-1" has 2 operators. Every way to parenthesize picks one operator to apply last.

recursion stack

empty

memo: sub-expression → all its values (0 stored)

empty

Variables
VariableValue
memo0
DepthFunction Call
Stack empty
0/17