Skip to content
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

[fix][golang] subsets #1573

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
45 changes: 26 additions & 19 deletions 多语言解法代码/solution_code.md
Original file line number Diff line number Diff line change
Expand Up @@ -61471,28 +61471,35 @@ class Solution {
```

```go
// by chatGPT (go)
//
// subsets is a function that returns all possible subsets of an array of integers.
// by mario_huang (go)
var res [][]int

// 记录回溯算法的递归路径
var track []int

// 主函数
func subsets(nums []int) [][]int {
res := [][]int{}
track := []int{}
backtrack(nums, 0, track, &res)
return res
res = [][]int{}
track = []int{}
backtrack(nums, 0)
return res
}

func backtrack(nums []int, start int, track []int, res *[][]int) {
temp := make([]int, len(track))
copy(temp, track)
*res = append(*res, temp)
for i := start; i < len(nums); i++ {
// 做选择
track = append(track, nums[i])
// 回溯
backtrack(nums, i+1, track, res)
// 撤销选择
track = track[:len(track)-1]
}
// 回溯算法核心函数,遍历子集问题的回溯树
func backtrack(nums []int, start int) {
// 前序位置,每个节点的值都是一个子集
temp := make([]int, len(track))
copy(temp, track)
res = append(res, temp)
// 回溯算法标准框架
for i := start; i < len(nums); i++ {
// 做选择
track = append(track, nums[i])
// 通过 start 参数控制树枝的遍历,避免产生重复的子集
backtrack(nums, i+1)
// 撤销选择
track = track[:len(track)-1]
}
}
```

Expand Down