Skip to content

22. Generate Parentheses#70

Open
hayashi-ay wants to merge 7 commits intomainfrom
hayashi-ay-patch-59
Open

22. Generate Parentheses#70
hayashi-ay wants to merge 7 commits intomainfrom
hayashi-ay-patch-59

Conversation

@hayashi-ay
Copy link
Copy Markdown
Owner

return
if num_left_brackets < 0 or num_left_brackets > n:
return
# append left brackets
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

このタイミングで num_left_brackets < n かどうか調べれば、 make_parenthesis() の呼び出し回数を減らせると思います。

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ありがとうございます。書き直しました。

class Solution:
    def generateParenthesis(self, n: int) -> List[str]:
        all_valid_parentheses = []
        partial_parenthesis = []

        def make_parenthesis(index, num_left_brackets):
            if index == n * 2:
                if num_left_brackets == 0:
                    all_valid_parentheses.append("".join(partial_parenthesis))
                return
            
            if num_left_brackets > 0:
                partial_parenthesis.append(')')
                make_parenthesis(index + 1, num_left_brackets - 1)
                partial_parenthesis.pop()
            
            if num_left_brackets < n:
                partial_parenthesis.append('(')
                make_parenthesis(index + 1, num_left_brackets + 1)
                partial_parenthesis.pop()
        
        make_parenthesis(0, 0)
        return all_valid_parentheses

make_parenthesis(index + 1, num_left_brackets + 1)
partial_parenthesis.pop()

# append right brackets
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

このタイミングで num_left_brackets > 0 かどうか調べれば、 make_parenthesis() の呼び出し回数を減らせると思います。

Copy link
Copy Markdown

@nodchip nodchip left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

よいと思います。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants