Skip to content
BytePatterns

Every Way To Bracket

MediumRecursion#divide-and-conquer#memoization~30m

Problem

A string holds non-negative integers joined by the operators +, - and *, with no spaces. Add brackets in every way that fully decides the order in which the operators are applied, evaluate each version, and return all the results in sorted order. Two different bracketings that give the same value both appear.

Examples

Input:  expr = "2-1-1"
Output: [0, 2]
Why:    (2-1)-1 is 0 and 2-(1-1) is 2
Input:  expr = "2*3-4*5"
Output: [-34, -14, -10, -10, 10]
Why:    five bracketings, two of which happen to agree
Input:  expr = "7"
Output: [7]
Why:    edge case, a lone number has exactly one way to be read

Hints

0 / 3

Stuck on the idea rather than the code? Memoization covers it.