Online store~25 min2s · 256 MBtarget O(C(k) k) for k numbers time, O(C(k)) spaceclassic twin: lc-241divide-and-conquer
A store app lets a manager type a price formula, such as 2*3-4*5, with plus, minus and times and no brackets. Different people add brackets in different ways, and each way can give a different result.
Before launch, the quality team wants a summary of every result a formula can take: how many different results, the smallest and the largest.
Your team lead says: Split the formula at each operator. Solve both sides, then combine every pair of values.
Write bracket_summary(formulas).
+, - and *, with no spaces and no brackets.formulas.Input: formulas = ["2*3-4"]
Output: [2, -2, 2]The formula has two operators, so it has two bracketings. The last operator applied is either * or -.
| Bracketing | Value |
|---|---|
| (2*(3-4)) | -2 |
| ((2*3)-4) | 2 |
The results are 2 and -2: two different results, with the smallest -2 and the largest 2.
Input: formulas = ["7", "4+5", "1+1+1"]
Output: [1, 7, 7, 1, 9, 9, 1, 3, 3]A single number has one result. The formula 1+1+1 has two bracketings that both give 3.
Input: formulas = ["2*3-4*5", "0*5-3"]
Output: [4, -34, 10, 2, -3, 0]The formula 2*3-4*5 has five bracketings and five different results.
1 ≤ formulas.length ≤ 2001 ≤ formulas[i].length ≤ 26+, - or *.A formula of 9 numbers has 1,430 bracketings, and one of 15 numbers has 2,674,440. The count grows by about 4 for each number. A list of 200 formulas of 9 numbers still holds only about 300,000 values, so the recursion is practical and brute force over strings is the slow part.