关于golang:Leetcode专题数组46全排列

6次阅读

共计 499 个字符,预计需要花费 2 分钟才能阅读完成。

力扣链接:
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
}
正文完
 0