Golang刷題 Leetcode 46. Permutations

題目:Permutations

Given a collection of distinct integers, return all possible permutations.

給一組不重複的整數,返回所有的排列

思路

回溯算法

需要注意的是,填充結果的時候,需要copy一個slice

code

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]
}
}

更多內容請移步我的repo:https://github.com/anakin/golang-leetcode


分享到:


相關文章: