Engineering platform~20 min2s · 256 MBtarget O(Catalan(n) × n) time, O(n) spaceclassic twin: lc-22backtracking
A build tool reads config files in which each block opens with ( and closes with ). QA wants to test the parser on every valid file with a given number of blocks and a limit on how deep blocks nest.
The test planner must write every file in a fixed order, and it must never spend time on a file that is already invalid.
Your team lead says: Generate every valid file for n blocks, with nesting no deeper than d.
Write nested_blocks(pairs, max_depth).
pairs opening brackets ( and pairs closing brackets ).) than (, and the whole text has equal numbers of both.( that are open at one moment. A returned text has depth at most max_depth.( before ).pairs = 12 has 208,012 texts, so the tests keep to that size.Input: pairs = 3, max_depth = 3
Output: ["((()))", "(()())", "(())()", "()(())", "()()()"]The five valid texts for 3 pairs come out in dictionary order. The search opens a bracket while some are left, and closes one only while one is open.
| Text | Calls made when it is saved |
|---|---|
| ((())) | 7 |
| (()()) | 11 |
| (())() | 14 |
| ()(()) | 19 |
| ()()() | 22 |
The search makes 22 calls in all. The answer has 5 texts.
Input: pairs = 3, max_depth = 2
Output: ["(()())", "(())()", "()(())", "()()()"]A depth limit of 2 removes ((())), which has depth 3. The search never opens a third bracket on top of two open ones.
| Text | Calls made when it is saved |
|---|---|
| (()()) | 7 |
| (())() | 10 |
| ()(()) | 15 |
| ()()() | 18 |
Input: pairs = 4, max_depth = 1
Output: ["()()()()"]With a depth limit of 1, a bracket must close before the next one opens. Only one text is left.
1 ≤ pairs ≤ 121 ≤ max_depth ≤ 12With 12 pairs there are 16,777,216 texts of 24 brackets, but only 208,012 of them are valid. The pruned search makes 1,033,411 calls. A max_depth above pairs has the same effect as max_depth = pairs.