在添加元素之前,我记录了每个元素。但是结果看起来好像覆盖了某些元素。
我不知道什么时候覆盖。
package main
import "fmt"
func main() {
graph := [][]int{
[]int{3, 1},
[]int{4, 6, 7, 2, 5},
[]int{4, 6, 3},
[]int{6, 4},
[]int{7, 6, 5},
[]int{6},
[]int{7},
[]int{},
}
fmt.Println(allPathsSourceTarget(graph))
}
func allPathsSourceTarget(graph [][]int) [][]int {
n := len(graph) - 1
result := make([][]int, 0, 200)
var pathRecord func(target, path []int)
pathRecord = func(target, path []int) {
if (len(target) == 0) && (path[len(path)-1] == n) {
fmt.Println("insert into", path) // should end with 7
result = append(result, path)
}
for _, v := range target {
pathRecord(graph[v], append(path, v))
}
}
for _, v := range graph[0] {
pathRecord(graph[v], []int{0, v})
}
return result
}
结果中的每个元素都应以7结尾。
答案 0 :(得分:2)
您的问题所在:
pathRecord(graph[v], append(path, v))
Go是如此“智能”,因此他试图重用相同的分片分配的内存,而您实际上更改了已经添加到结果中的路径。 ):
尝试以下方法:
newPath = make([]int, len(path))
copy(newPath, path)
pathRecord(graph[v], append(newPath, v))
答案 1 :(得分:2)
这对我有用。我认为这很奇怪,带有追加和切片
我假定内存支持“此追加”在切片充当指针的情况下传递到递归函数中
然后下次使用相同的内存,因此它会被覆盖
因此,您需要在每次递归时复制一份,以阻止其覆盖
pathRecord = func(target, path []int) {
if (len(target) == 0) && (path[len(path)-1] == n) {
var c []int = make([]int, len(path))
copy(c, path)
//fmt.Println("insert into", payload) // should end with 7
result = append(result, c)
}
for _, v := range target {
pathRecord(graph[v], append(path, v)) //this append
}
}