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.