Conversation
tokuhirat
reviewed
Oct 5, 2025
| # @param {Integer[]} nums | ||
| # @return {Integer[][]} | ||
| def subsets(nums) | ||
| subsets = [] |
There was a problem hiding this comment.
関数名と同じ変数名は避けたいと思いました。冪集合なので power_set もしくは単に results はいかがでしょうか。
Owner
Author
There was a problem hiding this comment.
コメントありがとうございます。power_setが良いですね。
potrue
reviewed
Oct 5, 2025
| end | ||
| subsets_helper.call(0, []) | ||
| subsets | ||
| end |
There was a problem hiding this comment.
読みやすいです。
bit全探索という考え方があり、それを使っても解けるので見てみると良いと思います。
整数をビットの列として解釈して、i番目のビットが1だったらi番目の要素が含まれる、という風に解釈する感じです。
def subsets(nums)
subsets = []
n = nums.size
# 0 から 2^n - 1 までの全パターンを試す
(0...(1 << n)).each do |bit|
subset = []
n.times do |i|
# i番目のビットが立っていれば、nums[i]を含める
subset << nums[i] if (bit >> i) & 1 == 1
end
subsets << subset
end
subsets
end
potrue
reviewed
Oct 5, 2025
| # @param {Integer[]} nums | ||
| # @return {Integer[][]} | ||
| def subsets(nums) | ||
| nums.inject([[]]) { |subsets, num| subsets.concat(subsets.map { |subset| subset + [num] }) } |
There was a problem hiding this comment.
reduceっぽい関数を使ってこのように書く書き方は思いついていませんでした。勉強になります 👀
コンパクトでいいですね。
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.
解いた問題
78. Subsets
使用言語
Ruby
次に解く問題
https://leetcode.com/problems/combination-sum/description/