update 0046.全排列: 替换 go 代码

This commit is contained in:
Yuhao Ju
2022-12-09 21:23:03 +08:00
committed by GitHub
parent 41007ef26c
commit 210ca488b4

View File

@ -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))
dfs(nums, 0)
return res return res
} }
func backTrack(nums []int,numsLen int,path []int) {
if len(nums)==0{ func dfs(nums []int, cur int) {
p:=make([]int,len(path)) if cur == len(nums) {
copy(p,path) tmp := make([]int, len(path))
res = append(res,p) copy(tmp, path)
res = append(res, tmp)
} }
for i:=0;i<numsLen;i++{ for i := 0; i < len(nums); i++ {
cur:=nums[i] if !st[i] {
path = append(path,cur) path = append(path, nums[i])
nums = append(nums[:i],nums[i+1:]...)//直接使用切片 st[i] = true
backTrack(nums,len(nums),path) dfs(nums, cur + 1)
nums = append(nums[:i],append([]int{cur},nums[i:]...)...)//回溯的时候切片也要复原,元素位置不能变 st[i] = false
path = path[:len(path)-1] path = path[:len(path)-1]
} }
} }
}
``` ```
### Javascript ### Javascript