46. 全排列
46. 全排列
题目描述:
给定一个 没有重复 数字的序列,返回其所有可能的全排列。
示例:
输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
思路:
一道经典dfs的题目,记得使用完之后得复原之前的样子,为什么要复制一份再append进去,因为这个path所指向的内存空间在之后还得用,所以path所引用的内容会变化
代码:
func permute(nums []int) [][]int {
if len(nums)==0{
return [][]int{}
}
res := [][]int{}
var recall func(path []int,start int)
recall = func(path []int,start int){
if len(path) == len(nums){
temp := make([]int, len(path))
copy(temp, path)
res = append(res, temp)
return
}
for i:=start;i<len(nums)&&i>=0;i++{
flag := false
//看是否有重复的数字
for _,v := range path{
if v ==nums[i]{
flag = true
break
}
}
if flag==true{
continue
}
path = append(path,nums[i])
recall(path,start)
path = path[:len(path)-1]
}
}
recall([]int{},0)
return res
}
代码效率:
执行用时:0 ms, 在所有 Go 提交中击败了100.00%的用户
内存消耗:2.7 MB, 在所有 Go 提交中击败了56.75%的用户
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!