|
| 1 | +# 4. Median of Two Sorted Arrays |
| 2 | + |
| 3 | +## Recursive Solution |
| 4 | +- Run-time: Less than O(2^2N) |
| 5 | +- Space: 2N |
| 6 | +- N = Given N |
| 7 | + |
| 8 | +Any time we deal with different choices, recursion should be the first thing to come to mind. |
| 9 | +This problem has a simple decision tree, whether to add a parenthesis or not. |
| 10 | +To figure that out, we need a few more items, we need to know the number of open versus closed parenthesis already used to form the result. |
| 11 | +Therefore, we are only considering valid parentheses as we recur down the decision tree. |
| 12 | + |
| 13 | +The run-time can be figured out by thinking about number of branches or children each node of tree will have, as well as the depth of the tree. |
| 14 | +So you can use the equation O(B^D) for most recursions. |
| 15 | +Since there are 2 decisions/branches and a depth of 2N, run-time can be considered O(2^2N). |
| 16 | + |
| 17 | +However, unlike other decision trees, this particular approach is only generating valid parentheses. |
| 18 | +So a result like '((((' or '))((' cannot be created if we were to instead traverse the entire decision. |
| 19 | +So a run-time of O(2^2N) isn't exactly correct, it is actually faster, again since we are only generating valid parentheses. |
| 20 | +It maybe difficult to come up with the actually run-time during an interview but you should at least mention this. |
| 21 | + |
| 22 | +``` |
| 23 | +class Solution: |
| 24 | + def generateParenthesis(self, n: int) -> List[str]: |
| 25 | +
|
| 26 | + def gen_helper(n_open, n_closed, stack): |
| 27 | + if n_open == n and n_closed == n: |
| 28 | + results.append(''.join(stack)) |
| 29 | + return |
| 30 | + if n_open != n: |
| 31 | + stack.append('(') |
| 32 | + gen_helper(n_open + 1, n_closed, stack) |
| 33 | + stack.pop() |
| 34 | + if n_open > n_closed and n_closed != n: |
| 35 | + stack.append(')') |
| 36 | + gen_helper(n_open, n_closed + 1, stack) |
| 37 | + stack.pop() |
| 38 | +
|
| 39 | + results = list() |
| 40 | + gen_helper(0, 0, []) |
| 41 | + return results |
| 42 | +``` |
0 commit comments