Create 78. Subsets.md#50
Open
fuga-98 wants to merge 1 commit into
Open
Conversation
oda
reviewed
May 23, 2025
Comment on lines
+28
to
+29
| result.append(target) | ||
| next_rest = rest_nums[:i] + rest_nums[i+1:] |
There was a problem hiding this comment.
この2行を
next_rest = rest_nums[i+1:]にしたら動きますかね。
hroc135
reviewed
Jun 5, 2025
| result = [] | ||
| for bit in range(1 << len(nums)): | ||
| subset = [] | ||
| for i in range(bit): |
There was a problem hiding this comment.
ここは for i in range(len(nums)) の方が意味として正確だと思います。
例えば nums = [1, 2, 3] とします。bit は 0 ~ 7 をレンジしますが、bit = 7 (2進数で111)のとき、if bit & (1 << 3) は知りたいですが、if bit & (1 << 7) には興味がないと思います。
hroc135
reviewed
Jun 5, 2025
| added = subset + [nums[index]] | ||
| return helper(subset, index + 1) + helper(added, index + 1) | ||
|
|
||
| return helper([], 0) |
There was a problem hiding this comment.
個人的には認知負荷が高いような気がして、原因は return helper(subset, index + 1) + helper(added, index + 1) にあるように思いました。例えば、nums = [1, 2, 3] のときに return [[]] + [[2]] となって [[], [2]] が返るわけですが、[] と [2] のペアに何か意味があるわけではないですね。
自分なら subset を随時入れていく箱をヘルパー関数の外に用意したくなりました。
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
result = []
def subsets_helper(subset, index):
if index == len(nums):
result.append(subset)
return
added_subset = subset + [nums[index]]
subsets_helper(subset, index+1)
subsets_helper(added_subset, index+1)
subsets_helper([], 0)
return result
Owner
Author
There was a problem hiding this comment.
副作用を嫌ってこう書きましたが、今見るとわかりにくいですね。
Owner
Author
There was a problem hiding this comment.
私は副作用のせいで時間を溶かしたことがなんどかあるので、ほかの人より避けたい気持ちが強いかもしれません。
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.
https://leetcode.com/problems/subsets/description/