Skip to content
Problem 241 · LeetCode 241(opens in a new tab)

Different Ways to Add Parentheses

MediumDynamic programming

You get a string expression made of non-negative whole numbers joined by the operators +, - and *. You may put brackets into it in any valid way, which decides the order the operators are applied in.

Return the value of every possible bracketing, one value per bracketing, in any order. Two bracketings that happen to give the same number both count, so a value can appear more than once.

Example 1

Input:  expression = "4-2*3"
Output: [-2, 6]
Why:    4-(2*3) = -2 and (4-2)*3 = 6
2 more examples and the constraints

Example 2

Input:  expression = "1+2*3-1"
Output: [5, 6, 6, 6, 8]
Why:    five bracketings; three of them give 6

Example 3

Input:  expression = "15"
Output: [15]
Why:    no operator, so there is one way

Constraints

  • 1 ≤ length of expression ≤ 20
  • It holds only digits and the characters +, - and *
  • Every number is between 0 and 99 and has no sign in front
  • Every result fits in a 32-bit integer, and there are at most 10,000 of them

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Split at every operatorO(n · Cₙ)
  2. Split with a memoO(n · Cₙ)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 10 numbersVerdict
Split at every operatorO(n · Cₙ)
Passes; rebuilds pieces
Split with a memoO(n · Cₙ)
Best; each piece once

n = number of operators. Cₙ = the Catalan number, the count of bracketings (4,862 for 9 operators).

Edge cases to test

  • No operator. "15" has one bracketing, so the answer is [15].
  • Multi-digit numbers. Split only at operators, never between digits: "10+20*3" gives 90 and 70.
  • Equal results. "1+1+1" gives [3, 3]: two bracketings, so the value appears twice.
  • Negative results. Subtraction can go below 0 even though the input has no signs, as in "0*5-7".

Common mistakes

  • Removing duplicate values; each bracketing must give its own entry.
  • Parsing one digit at a time, which breaks numbers like 10 or 99.
  • Calling the right-side recursion inside the loop over left values, which repeats it for every left value.

How to talk through it

  1. 1Clarify. Do duplicate values count separately? Which operators appear? Can numbers have more than one digit?
  2. 2Find the last operator. Every bracketing has one operator applied last; it splits the string into two smaller copies of the problem.
  3. 3Combine the sides. Every left value with every right value, through that operator.
  4. 4Add a memo. There are only O(n²) different pieces; store each list the first time.
  5. 5Test out loud. Run "15", "1+1+1" for duplicates, and "10+20*3" for two-digit numbers.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?