Generate Parentheses
LeetCode 22 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్త్రూ
Add '(' if left < n; add ')' if right < left.
నేను Generate Parentheses (LeetCode 22) ను ఇలా పరిష్కరించాను — Generate / Build Strings ప్యాటర్న్లోని ఒక మధ్యస్థం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.
కింది వివరణ ఇంగ్లీష్లో ఉంది.
Intuition
Build the string character by character. You may add '(' while fewer than n are used, and ')' only if it would close an open one (closing count < opening count). That rule generates exactly the valid strings.
Approach
- 1
Length 2n → record.
- 2
If left < n, append '(' and recurse.
- 3
If right < left, append ')' and recurse.
- 4
Pop after each recursion.
నేను ఎలా పరిష్కరించాను
Backtracking with countsPythonCatalan-number time
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
#maintain ( for left parentheses
#maintain ) for right parentheses
res = []
def dfs(cur_string,left_counter,right_counter):
if len(cur_string)==2*n:
res.append("".join(cur_string))
if left_counter<n:
cur_string.append("(")
dfs(cur_string,left_counter+1,right_counter)
cur_string.pop()
#when come back remove (
if left_counter>right_counter: # we have more (
cur_string.append(")")
dfs(cur_string,left_counter,right_counter+1)
#remove when come back
cur_string.pop()
dfs([],0,0)
return resGenerate Parentheses — తరచూ అడిగే ప్రశ్నలు
Generate Parentheses వెనుక ఉన్న intuition ఏమిటి?
Build the string character by character. You may add '(' while fewer than n are used, and ')' only if it would close an open one (closing count < opening count). That rule generates exactly the valid strings.
Generate Parentheses (LeetCode 22) ను ఎలా పరిష్కరించాలి?
1. Length 2n → record. 2. If left < n, append '(' and recurse. 3. If right < left, append ')' and recurse. 4. Pop after each recursion.
Generate Parentheses యొక్క time, space complexity ఎంత?
Time: O(4ⁿ / √n). Space: O(n). (Accepted approach: Backtracking with counts.)
Generate Parentheses లో సాధారణ పొరపాట్లు ఏమిటి?
Never let closes exceed opens.