Generate N valid parentheses III
Problem Statement Get all valid permutations of l pairs of (), m pairs of <> and n pairs of {}, subject to the priority restriction: {} higher than <> higher than ().
Assumptions l, m, n >= 0 l + m + n >= 0
Examples l = 1, m = 1, n = 0, all the valid permutations are ["()<>", "<()>", "<>()"]. l = 2, m = 0, n = 1, all the valid permutations are [“()(){}”, “(){()}”, “(){}()”, “{()()}”, “{()}()”, “{}()()”].
Base Case:
When no more braces to add && all braces are completed. Add to result
Recursive Rule:
Add left brace until no more to add (both of)
No remaining capacity No remaining with low enough priority
complete with right brace
undo right brace
undo left brace
Key Takeaways Identical to previous solution expect lines 33-37 as we must check if a left branch is possible, i.e. count is valid and priority of incoming left brace is (strictly) less than the right brace on the stack. Plainly, we cannot insert a high priority left brace (incoming) into a nested low priority right brace (stack).
Last updated
Was this helpful?