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.