我试图学习Go但是我无法弄清楚为什么递归调用堆栈末尾的代码会返回一个空切片,有什么帮助吗?此外One One
似乎甚至无法在调试器中注册。
preceding keyword
答案 0 :(得分:1)
这是让代码附加切片的解决方案。在GO中,如果递归传递切片,则必须通过引用传递它。因此,这解决了您遇到的问题,即代码将返回空切片。但是你的算法似乎不符合你期望的结果。
func main() {
input := [3]int{4, 6, 7}
// expected [[6,7],[4,6,7],[4,6],[4,7]]
fmt.Println(findSubsequences(input))
}
func findSubsequences(nums [3]int) [][]int {
res := [][]int{}
list := []int{}
fmt.Print(nums)
findSubsequence(&res, list, nums, 0)
return res
}
func findSubsequence(res *[][]int, list []int, nums [3]int, id int) [][]int {
var tmp []int
if len(list) > 1 {
tmp = make([]int, len(list))
copy(tmp, list)
fmt.Println(tmp)
*res = append(*res, tmp)
}
var unique []int
for i := id; i < len(nums); i++ {
if id > 0 && nums[i] < nums[id-1] {
continue // skip non-increase
}
if contains(unique, nums[i]) {
continue // skip duplicate
}
unique = append(unique, nums[i])
list = append(list, nums[i])
findSubsequence(res, list, nums, id+1)
list = list[:len(list)-1]
}
return *res
}
func contains(s []int, e int) bool {
for _, a := range s {
if a == e || a >e {
return true
}
}
return false
}
答案 1 :(得分:0)
我最后使用了全局变量,但仍然不行,它比Java工作得慢,无论如何这里是代码。
var res = [][]int{}
var list = []int{}
func findSubsequences(nums [3]int) [][]int {
findSubsequence(nums, 0)
return res
}
func findSubsequence(nums [3]int, id int) {
if len(list) > 1 {
tmp := make([]int, len(list))
copy(tmp, list)
res = append(res, tmp)
}
var unique []int
for i := id; i < len(nums); i++ {
if id > 0 && nums[i] < nums[id-1] {
continue // skip non-increase
}
if contains(unique, nums[i]) {
continue // skip duplicate
}
unique = append(unique, nums[i])
list = append(list, nums[i])
findSubsequence(nums, i+1)
list = list[:len(list)-1]
}
}
func contains(s []int, e int) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}