递归实现全排列

 

 

https://leetcode.cn/problems/permutations/

 

var ans [][]int
var vis map[int]bool
func permute(nums []int) [][]int {
    path:=make([]int,0)
    ans=make([][]int,0)
    vis=make(map[int]bool)
    dfs(path,nums)
    return ans
}

func dfs(path,nums []int) {
        if len(path) == len(nums) {
            temp := make([]int, len(path))
            copy(temp, path)
            ans = append(ans, temp)
            return
        }
        for _, n := range nums {
            if vis[n] {
                continue
            }
            path = append(path, n)
            vis[n] = true
            dfs(path,nums)
            path = path[:len(path)-1]
            vis[n] = false
        }
    }

 

 
posted @ 2022-07-10 22:08  知道了呀~  阅读(58)  评论(0编辑  收藏  举报