Leetcode专题[数组]-46-全排列

力扣链接:
https://leetcode-cn.com/probl...
解题思路:

  1. 回溯算法
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) {
        // 切片内存拷贝
        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
}

你可能感兴趣的:(golang)