Skip to content

797. 所有可能的路径

题目链接:https://leetcode.cn/problems/all-paths-from-source-to-target/description/

go
func allPathsSourceTarget(graph [][]int) (ans [][]int) {
    stk := []int{0}

    var dfs func(int)
    dfs = func(x int) {
        if x == len(graph)-1 {
            ans = append(ans, append([]int(nil), stk...)) //这里相当于拷贝一个数组
            return
        }

        for _, y := range graph[x] {
            stk = append(stk, y)
            dfs(y)
            stk = stk[:len(stk)-1] // 回溯
        }
    }
    dfs(0)
    return
}
本站访客数 人次 本站总访问量