Generate Parentheses - Leetcode 22 - Recursive Backtracking (Python)

preview_player
Показать описание


Please check my playlists for free DSA problem solutions:

My Favorite Courses:

Data Structures & Algorithms:

Python:

Web Dev / Full Stack:

Cloud Development:

Game Development:

SQL & Data Science:

Machine Learning & AI:
Рекомендации по теме
Комментарии
Автор

Master Data Structures & Algorithms For FREE at AlgoMap.io!

GregHogg
Автор

Love you explanations, by far the best on the internet! It makes these problems so much easier to understand and code. Please upload DSA 150 as these will be more helpful for those preparing for interviews.

saaddude
Автор

When im stuck at backtracking i listen to your explanations without looking at your code and in the middle of the explanation something just clicks and then i go and am able to solve it immediately. Hopefully with time i can start solving without the need of your explanations ^^ Thanks for everything tho

Redaxi
Автор

Thanks, Greg! Btw, wanna share the modified version using a string, instead of a list. We can just append each character "(" or ")" to the string in the function parameter.

class Solution:
def generateParenthesis(self, n: int) -> List[str]:
result = []


def rec(n_open, n_close, parenthesis):
if len(parenthesis) == (2*n):
result.append(parenthesis)
return

if n_open < n:
rec(n_open+1, n_close, parenthesis+"(")

if n_close < n_open:
rec(n_open, n_close+1, parenthesis+")")

rec(n_open=0, n_close=0, parenthesis="")

return result

ArdianUmam
Автор

Subbed. Great explanation. Also base condition could be if (open==n && closed==n) then append.

SaPpHiRe
Автор

Thanks for the video! What software did you use for the whiteboarding? Do you use a special pen or just a mouse to write?

SelftaughtSoftwareEngineer
Автор

i dont understand two things: 1. why do we need to pop after we add a parenthesis. if we pop, wouldn't sol be an empty list (and then how an empty list would be used in appending to ans?)? 2. why would this algorithm not stop after getting the first combination "((()))"?

anton_melnikov
Автор

With n=8, there are 1430 combinations. That's 1430 combinations of size (2*n). The space complexity is not O(n).

tushitapatel