Skip to content

Conversation

@akmhmgc
Copy link
Owner

@akmhmgc akmhmgc commented Oct 7, 2025

解いた問題

22. Generate Parentheses

使用言語

Ruby

次に解く問題

703. Kth Largest Element in a Stream

@akmhmgc akmhmgc added the ruby label Oct 7, 2025
# @return {String[]}
def generate_parenthesis(n)
result = []
generate_parenthesis_helper = lambda do |left, right, parenthesis|

Choose a reason for hiding this comment

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

個人的には num_left のように個数であることがわかるように書きたいなと思いました。

# @return {String[]}
def generate_parenthesis(n)
combinations = []
generate_parenthesis_helper = lambda do |parenthesis, left ,right|
Copy link

Choose a reason for hiding this comment

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

left, right とすることをお勧めいたします。

Copy link
Owner Author

Choose a reason for hiding this comment

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

コメントありがとうございます。
parenthesisは引数に渡さずに再帰関数の外側に置くということですかね。
これは、parenthesisに破壊的変更を加えていて予想しにくいので、関数の引数として渡さない方が良いという考えのもとでしょうか?

# @param {Integer} n
# @return {String[]}
def generate_parenthesis(n)
    combinations = []
    parenthesis = []
    generate_parenthesis_helper = lambda do |left ,right|
        if right == n
            combinations << parenthesis.join
            return
        end
        if left < n
            parenthesis << "("
            generate_parenthesis_helper.call(left + 1, right)
            parenthesis.pop
        end
        if right < left
            parenthesis << ")"
            generate_parenthesis_helper.call(left, right + 1)
            parenthesis.pop
        end
    end
    generate_parenthesis_helper.call(0, 0)
    combinations
end

Copy link

Choose a reason for hiding this comment

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

単純にスペースをどこに置くかというスタイルの問題じゃないですかね?

Copy link
Owner Author

Choose a reason for hiding this comment

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

ああ、そういうことでしたか、ありがとうございます。

end
end
generate_parenthesis_helper.call(0, 0, [])
result
Copy link

@potrue potrue Oct 10, 2025

Choose a reason for hiding this comment

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

読みやすいです。自分もleft, rightはindexのイメージがあるのでnum_left, num_rightの方がいいかもしれないです。num_open, num_closeでもいいかもしれません。

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants