Add Generate Parentheses solution and explanation#12
Open
yakataN wants to merge 1 commit into
Open
Conversation
potrue
reviewed
Sep 10, 2025
| generated_parenthesis.pop() | ||
|
|
||
| generate_parenthesis_helper(0, 0, []) | ||
| return result |
There was a problem hiding this comment.
読みやすいと思います。個人的には変数名にgeneratedやparenthesisが若干くどいような気もしますが好みの範囲かもしれません(used_open: int, used_close: int, parenthesis: List[str]ぐらいでもいいような気がします)
tokuhirat
reviewed
Sep 11, 2025
| return list(result) | ||
|
|
||
| return generate_parenthesis_helper(n) | ||
| ``` |
There was a problem hiding this comment.
ヘルパー関数使わずに書けますね。
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
if n == 0:
return [""]
result = set()
for pattern in self.generateParenthesis(n - 1):
for index in range(len(pattern) + 1):
result.add(pattern[:index] + "()" + pattern[index:])
return list(result)
tokuhirat
reviewed
Sep 11, 2025
| for pattern in parentheses[i]: | ||
| for index in range(len(pattern)+1): | ||
| parentheses[i+1].add(pattern[:index]+"()"+pattern[index:]) | ||
| return list(parentheses[-1]) |
There was a problem hiding this comment.
i-1のパターンからiのパターンを生み出しているので直近のパターンを持っていれば十分で、以下のように i を使わずに済みます。
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
parentheses = {""}
for _ in range(n):
next_parentheses = set()
for pattern in parentheses:
for index in range(len(pattern) + 1):
next_parentheses.add(pattern[:index] + "()" + pattern[index:])
parentheses = next_parentheses
return list(parentheses)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
This problem:
https://leetcode.com/problems/generate-parentheses/
Next problem:
https://leetcode.com/problems/kth-largest-element-in-a-stream/