mirror of
https://github.com/donnemartin/interactive-coding-challenges.git
synced 2024-03-22 13:11:13 +08:00
Updated n-pairs parentheses solution information
This commit is contained in:
parent
30158749c9
commit
fa85e1f7dd
|
@ -41,7 +41,7 @@
|
|||
"source": [
|
||||
"## Test Cases\n",
|
||||
"\n",
|
||||
"* 0 -> ''\n",
|
||||
"* 0 -> ' '\n",
|
||||
"* 1 -> ()\n",
|
||||
"* 2 -> (()), ()()\n",
|
||||
"* 3 -> ((())), (()()), (())(), ()(()), ()()()"
|
||||
|
@ -52,13 +52,26 @@
|
|||
"metadata": {},
|
||||
"source": [
|
||||
"# Algorithm\n",
|
||||
"* If no_of_left == 0 and no_of right == 0, add pair_string to result\n",
|
||||
"* Else \n",
|
||||
" * If (no_left > 0), parentheses_util(no_left - 1, no_right, pair_string + '(', result)\n",
|
||||
" * If (no_right > no_left), parentheses_util(no_left, no_right - 1, pair_string + ')', result)\n",
|
||||
"\n",
|
||||
"Let `l` and `r` denote the number of left and right parentheses remaining at any given point. \n",
|
||||
"The algorithm makes use of the following conditions applied recursively:\n",
|
||||
"* Left braces can be inserted any time, as long as we do not exhaust them i.e. `l > 0`.\n",
|
||||
"* Right braces can be inserted, as long as the number of right braces remaining is greater than the left braces remaining i.e. `r > l`. Violation of the aforementioned condition produces an unbalanced string of parentheses.\n",
|
||||
"* If both left and right braces have been exhausted i.e. `l = 0 and r = 0`, then the resultant string produced is balanced.\n",
|
||||
"\n",
|
||||
"The algorithm can be rephrased as:\n",
|
||||
"* Base case: `l = 0 and r = 0`\n",
|
||||
" - Add the string generated to the result set\n",
|
||||
"* Case 1: `l > 0`\n",
|
||||
" - Add a left parenthesis to the parentheses string.\n",
|
||||
" - Call parentheses_util(l - 1, r, new_string, result_set)\n",
|
||||
"* Case 2: `r > l`\n",
|
||||
" - Add a right parenthesis to the parentheses string.\n",
|
||||
" - Call parentheses_util(l, r - 1, new_string, result_set)\n",
|
||||
"\n",
|
||||
"Complexity:\n",
|
||||
"* Time: O(4^n/n^(3/2)) "
|
||||
"* Time: `O(4^n/n^(3/2))`. See [Catalan numbers](https://en.wikipedia.org/wiki/Catalan_number#Applications_in_combinatorics)\n",
|
||||
"* Space complexity: `O(n)` (Due to the implicit call stack storing a maximum of 2n function calls)"
|
||||
]
|
||||
},
|
||||
{
|
||||
|
@ -70,7 +83,7 @@
|
|||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 5,
|
||||
"execution_count": 1,
|
||||
"metadata": {
|
||||
"collapsed": true
|
||||
},
|
||||
|
@ -103,7 +116,7 @@
|
|||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 6,
|
||||
"execution_count": 2,
|
||||
"metadata": {
|
||||
"collapsed": false
|
||||
},
|
||||
|
|
Loading…
Reference in New Issue
Block a user