u
This commit is contained in:
@@ -0,0 +1,41 @@
|
||||
package top100liked
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// https://leetcode.cn/problems/permutations?envType=study-plan-v2&envId=top-100-liked
|
||||
|
||||
func permute(nums []int) [][]int {
|
||||
l := len(nums)
|
||||
fact := 1
|
||||
for i := 2; i <= l; i++ {
|
||||
fact *= i
|
||||
}
|
||||
res := make([][]int, 0, fact)
|
||||
var helper func(nums []int, used []bool, r []int)
|
||||
helper = func(nums []int, used []bool, r []int) {
|
||||
for i, v := range used {
|
||||
if !v {
|
||||
used[i] = true
|
||||
r = append(r, nums[i])
|
||||
if len(r) == l {
|
||||
cp := make([]int, l)
|
||||
copy(cp, r)
|
||||
res = append(res, cp)
|
||||
} else {
|
||||
helper(nums, used, r)
|
||||
}
|
||||
r = r[:len(r)-1]
|
||||
used[i] = false
|
||||
}
|
||||
}
|
||||
}
|
||||
helper(nums, make([]bool, l), make([]int, 0))
|
||||
return res
|
||||
}
|
||||
|
||||
func Test(t *testing.T) {
|
||||
fmt.Printf("%+v", permute([]int{5, 4, 6, 2}))
|
||||
}
|
||||
Reference in New Issue
Block a user