All problems
0981MediumMathStringDynamic ProgrammingRecursionMemoizationBracket Sequences

Every Value a Sum Can Be Grouped Into

Tracked in this browser only
Write code

Trains the technique from

LeetCode 241Different Ways to Add Parentheses

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

An arithmetic line is given as expression, made of whole numbers and the signs '+', '-' and '*', with no spaces and no signs marking a number as negative.

Brackets may be put anywhere, so long as the result is a valid arithmetic line, which fixes the order the operations happen in. Different bracketings may give different values.

Return the values from every possible bracketing, in increasing order. A value appears as many times as there are bracketings producing it.

Examples

Example 1

Input
expression = "2-3-4"
Output
[-5, 3]

Bracketing the first subtraction gives minus five, and bracketing the second gives three.

Example 2

Input
expression = "99"
Output
[99]

There is no sign to bracket, so the line takes its own value.

Example 3

Input
expression = "1+1"
Output
[2]

One sign means one bracketing.

Constraints

  • 1 <= expression.length <= 20
  • expression consists of digits and the signs '+', '-' and '*' only
  • Every whole number in expression is between 0 and 99
  • No number in expression is marked with a leading sign

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def diff_ways_to_compute(expression: str) -> list[int]:
Java
public List<Integer> diffWaysToCompute(String expression)
September 7
Apply