Skip to content

Conversation

@akmhmgc
Copy link
Owner

@akmhmgc akmhmgc commented Oct 5, 2025

解いた問題

78. Subsets

使用言語

Ruby

次に解く問題

https://leetcode.com/problems/combination-sum/description/

@akmhmgc akmhmgc added the ruby label Oct 5, 2025
@akmhmgc akmhmgc self-assigned this Oct 5, 2025
# @param {Integer[]} nums
# @return {Integer[][]}
def subsets(nums)
subsets = []

Choose a reason for hiding this comment

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

関数名と同じ変数名は避けたいと思いました。冪集合なので power_set もしくは単に results はいかがでしょうか。

Copy link
Owner Author

Choose a reason for hiding this comment

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

コメントありがとうございます。power_setが良いですね。

end
subsets_helper.call(0, [])
subsets
end
Copy link

Choose a reason for hiding this comment

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

読みやすいです。
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

# @param {Integer[]} nums
# @return {Integer[][]}
def subsets(nums)
nums.inject([[]]) { |subsets, num| subsets.concat(subsets.map { |subset| subset + [num] }) }
Copy link

Choose a reason for hiding this comment

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

reduceっぽい関数を使ってこのように書く書き方は思いついていませんでした。勉強になります 👀
コンパクトでいいですね。

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.

4 participants