美文网首页leetcode
46. Permutations.go

46. Permutations.go

作者: AnakinSun | 来源:发表于2019-03-22 13:33 被阅读2次

    回溯算法
    需要注意的是,填充结果的时候,需要copy一个slice

    func permute(nums []int) [][]int {
        var ret [][]int
        l := len(nums)
        if l == 0 {
            return ret
        }
        helper(nums, 0, l-1, &ret)
        return ret
    }
    
    func helper(nums []int, begin, end int, ret *[][]int) {
        if begin == end {
            t := make([]int, len(nums))
            copy(t, nums) //这里一定要copy
            *ret = append(*ret, t)
            return
        }
    
        for i := begin; i <= end; i++ {
            nums[begin], nums[i] = nums[i], nums[begin]
            helper(nums, begin+1, end, ret)
            nums[begin], nums[i] = nums[i], nums[begin]
        }
    }
    

    相关文章

      网友评论

        本文标题:46. Permutations.go

        本文链接:https://www.haomeiwen.com/subject/ytilvqtx.html