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.