mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 07:35:35 +08:00
update 0046.全排列: 替换 go 代码
This commit is contained in:
@ -275,29 +275,34 @@ class Solution:
|
||||
|
||||
### Go
|
||||
```Go
|
||||
var res [][]int
|
||||
var (
|
||||
res [][]int
|
||||
path []int
|
||||
st []bool // state的缩写
|
||||
)
|
||||
func permute(nums []int) [][]int {
|
||||
res = [][]int{}
|
||||
backTrack(nums,len(nums),[]int{})
|
||||
return res
|
||||
}
|
||||
func backTrack(nums []int,numsLen int,path []int) {
|
||||
if len(nums)==0{
|
||||
p:=make([]int,len(path))
|
||||
copy(p,path)
|
||||
res = append(res,p)
|
||||
}
|
||||
for i:=0;i<numsLen;i++{
|
||||
cur:=nums[i]
|
||||
path = append(path,cur)
|
||||
nums = append(nums[:i],nums[i+1:]...)//直接使用切片
|
||||
backTrack(nums,len(nums),path)
|
||||
nums = append(nums[:i],append([]int{cur},nums[i:]...)...)//回溯的时候切片也要复原,元素位置不能变
|
||||
path = path[:len(path)-1]
|
||||
|
||||
}
|
||||
res, path = make([][]int, 0), make([]int, 0, len(nums))
|
||||
st = make([]bool, len(nums))
|
||||
dfs(nums, 0)
|
||||
return res
|
||||
}
|
||||
|
||||
func dfs(nums []int, cur int) {
|
||||
if cur == len(nums) {
|
||||
tmp := make([]int, len(path))
|
||||
copy(tmp, path)
|
||||
res = append(res, tmp)
|
||||
}
|
||||
for i := 0; i < len(nums); i++ {
|
||||
if !st[i] {
|
||||
path = append(path, nums[i])
|
||||
st[i] = true
|
||||
dfs(nums, cur + 1)
|
||||
st[i] = false
|
||||
path = path[:len(path)-1]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Javascript
|
||||
|
Reference in New Issue
Block a user