Tensorum
YouTubeশেখা শুরু করুন
LeetCode 22 · Generate / Build Strings

Generate Parentheses

LeetCode 22 · মাঝারি · সমাধান, intuition ও ধাপে ধাপে ওয়াকথ্রু

Add '(' if left < n; add ')' if right < left.

মাঝারিStringDynamic ProgrammingBacktrackingBracket Sequences
LeetCode-এ খুলুন ↗

আমি 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. 1

    Length 2n → record.

  2. 2

    If left < n, append '(' and recurse.

  3. 3

    If right < left, append ')' and recurse.

  4. 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 res
স্টেপ-থ্রু লোড হচ্ছে…

Generate 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.