Skip to content

Create 78. Subsets.md#50

Open
fuga-98 wants to merge 1 commit into
mainfrom
78.-Subsets
Open

Create 78. Subsets.md#50
fuga-98 wants to merge 1 commit into
mainfrom
78.-Subsets

Conversation

@fuga-98
Copy link
Copy Markdown
Owner

@fuga-98 fuga-98 commented May 22, 2025

Comment thread 78. Subsets.md
Comment on lines +28 to +29
result.append(target)
next_rest = rest_nums[:i] + rest_nums[i+1:]
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

この2行を

next_rest = rest_nums[i+1:]

にしたら動きますかね。

Comment thread 78. Subsets.md
result = []
for bit in range(1 << len(nums)):
subset = []
for i in range(bit):
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

ここは 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) には興味がないと思います。

Comment thread 78. Subsets.md
added = subset + [nums[index]]
return helper(subset, index + 1) + helper(added, index + 1)

return helper([], 0)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

個人的には認知負荷が高いような気がして、原因は 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

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.

副作用を嫌ってこう書きましたが、今見るとわかりにくいですね。

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.

私は副作用のせいで時間を溶かしたことがなんどかあるので、ほかの人より避けたい気持ちが強いかもしれません。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants