mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
update 0046.全排列: 替换 go 代码
This commit is contained in:
@ -275,29 +275,34 @@ class Solution:
|
|||||||
|
|
||||||
### Go
|
### Go
|
||||||
```Go
|
```Go
|
||||||
var res [][]int
|
var (
|
||||||
|
res [][]int
|
||||||
|
path []int
|
||||||
|
st []bool // state的缩写
|
||||||
|
)
|
||||||
func permute(nums []int) [][]int {
|
func permute(nums []int) [][]int {
|
||||||
res = [][]int{}
|
res, path = make([][]int, 0), make([]int, 0, len(nums))
|
||||||
backTrack(nums,len(nums),[]int{})
|
st = make([]bool, len(nums))
|
||||||
return res
|
dfs(nums, 0)
|
||||||
}
|
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]
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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
|
### Javascript
|
||||||
|
Reference in New Issue
Block a user