当前位置:网站首页>Leetcode topic [array] -46- full arrangement

Leetcode topic [array] -46- full arrangement

2022-06-24 17:33:00 LabRat

Force link :
https://leetcode-cn.com/probl...
Their thinking :

  1. Backtracking algorithm
func permute(nums []int) [][]int {
    res := [][]int{}
    backtrack(&res, nums, []int{})
    return res
}

func backtrack(res *[][]int, nums, path []int) {
    if len(path) == len(nums) {
        //  Slice memory copy 
        newPath := make([]int, len(path))
        copy(newPath, path)
        *res = append(*res, newPath)
        return
    }
    for i := 0; i < len(nums); i++ {
        if contains(path, nums[i]) {
            continue
        }
        path = append(path, nums[i])
        backtrack(res, nums, path)
        path = path[:len(path) - 1]
    }
}

func contains(nums []int, num int) bool {
    for _, v := range nums {
        if v == num {
            return true
        }
    }
    return false
}
原网站

版权声明
本文为[LabRat]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202211543106635.html

随机推荐