Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 78 additions & 0 deletions 78. Subsets/78. Subsets.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
# 78. Subsets
## STEP1
- 何も見ずに解いてみる
- bit全探索で列挙すればよい
```python
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
n = len(nums)
power_set = []
for i in range(1 << n):
subset = []
for bit, num in enumerate(nums):
if i & (1 << bit) != 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.

if i & (1 << bit) でもいいかもしれませんね。

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.

コメントありがとうございます。
i & (1 << bit) は int なので 0 と比較するのがわかりやすく、安全かなと思っています。
https://google.github.io/styleguide/pyguide.html#2144-decision

subset.append(num)
power_set.append(subset)
return power_set
```

## STEP2
### プルリクやドキュメントを参照
- https://github.com/olsen-blue/Arai60/pull/52/files
- STEP1 で書いた i は bit_mask の方がわかりやすい。
- backtrack での書き方。自力で書こうとした時は毎回 nums の要素を走査しようとしてできなかった。樹形図を思い浮かべてしまったが筋が悪かった。各 index の数字を使うか使わないかを探索すればよいのですね。bit全探索と同じだが、0,1のパネルの裏表を順に試していくイメージ。
- 引き継ぐ subset を引数にするか関数外部に書くか。個人的には引数にした方がわかりやすいと思う。関数外部に書いた場合には副作用が起きるが、引数にした場合は実装が正しければ関数は副作用を持たないため。
```python
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
power_set = []

def generate_subset(index: int, subset: list[int]) -> None:
if index == len(nums):
power_set.append(subset[:])
return
generate_subset(index + 1, subset)
subset.append(nums[index])
generate_subset(index + 1, subset)
subset.pop()

generate_subset(0, [])
return power_set
```

- https://github.com/hayashi-ay/leetcode/pull/63/files#diff-ddd8c09ee41837c8d5bde978403f850a0b08217fb8ec8eac6d0f2ae10e369d04R91
- シンプルでよい。これまでできた subsets に新しい num を追加した subset を追加する。
```python
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
power_set = [[]]
for num in nums:
subsets = [subset + [num] for subset in power_set]
power_set.extend(subsets)
return power_set
```
- https://github.com/fhiyo/leetcode/pull/51/files#r1690146921
- かわいさ、感じとれず、、、

## STEP3
### 3回ミスなく書く
練習として backtrack で書く。
```python
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
power_set = []

def generate_subset(index: int, subset: list[int]) -> None:
if index == len(nums):
power_set.append(subset[:])
return
generate_subset(index + 1, subset)
subset.append(nums[index])
generate_subset(index + 1, subset)
subset.pop()

generate_subset(0, [])
return power_set
```

2分,2分,2分で3回Accept