Skip to content

Conversation

hroc135
Copy link
Owner

@hroc135 hroc135 commented Apr 14, 2025

```

#### 2e
- 2d を末尾再帰最適化できるようにした
Copy link

Choose a reason for hiding this comment

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

良いと思います。

末尾再帰は、無限ループで囲って引数を代入に変えるとループに直ります。対応関係を意識するといいかもしれません。

Copy link
Owner Author

Choose a reason for hiding this comment

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

末尾再帰はループに直しやすいですね。
書いてみました。

func subsets(nums []int) [][]int {
    index := 0
    subsetsBeforeIndex := [][]int{{}}
    for {
        if index == len(nums) {
            return subsetsBeforeIndex
        }
        num := nums[index]
        subsetsNumTail := [][]int{}
        for _, subset := range subsetsBeforeIndex {
            newSubset := slices.Concat(subset, []int{num})
            subsetsNumTail = append(subsetsNumTail, newSubset)
        }
        subsetsBeforeIndex = append(subsetsBeforeIndex, subsetsNumTail...)
        index++
    }
    panic("unreachable")
}

無限ループを numsを舐めるループに変えれば step3 のコードになりますね。

Comment on lines +240 to +242
- Shallow copy vs Deep copy
- shallow: コピーされた要素は元のものと同じ参照を持つ
- deep: 完全に新しいオブジェクトを生成する

Choose a reason for hiding this comment

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

deep copy、この問題も参考になりました。
https://leetcode.com/problems/clone-graph/description/

Copy link
Owner Author

Choose a reason for hiding this comment

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

共有ありがとうございます!grind75に含まれているのですね。

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