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.