Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

22. Generate Parentheses #70

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open

22. Generate Parentheses #70

wants to merge 7 commits into from

Conversation

hayashi-ay
Copy link
Owner

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

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

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

@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