Skip to content

78. Subsets - #45

Open
akmhmgc wants to merge 1 commit into
mainfrom
78
Open

78. Subsets#45
akmhmgc wants to merge 1 commit into
mainfrom
78

Conversation

@akmhmgc

@akmhmgc akmhmgc commented Oct 5, 2025

Copy link
Copy Markdown
Owner

解いた問題

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
Comment thread 78/step3.md
# @param {Integer[]} nums
# @return {Integer[][]}
def subsets(nums)
subsets = []

Copy link
Copy Markdown

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
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

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

Comment thread 78/step3.md
end
subsets_helper.call(0, [])
subsets
end

Copy link
Copy Markdown

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

Comment thread 78/step1.md
# @param {Integer[]} nums
# @return {Integer[][]}
def subsets(nums)
nums.inject([[]]) { |subsets, num| subsets.concat(subsets.map { |subset| subset + [num] }) }

Copy link
Copy Markdown

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.

3 participants