-
Notifications
You must be signed in to change notification settings - Fork 0
78. Subsets #45
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
78. Subsets #45
Conversation
| # @param {Integer[]} nums | ||
| # @return {Integer[][]} | ||
| def subsets(nums) | ||
| subsets = [] |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
関数名と同じ変数名は避けたいと思いました。冪集合なので power_set もしくは単に results はいかがでしょうか。
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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] }) } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
reduceっぽい関数を使ってこのように書く書き方は思いついていませんでした。勉強になります 👀
コンパクトでいいですね。
解いた問題
78. Subsets
使用言語
Ruby
次に解く問題
https://leetcode.com/problems/combination-sum/description/