This commit is contained in:
2026-07-02 13:48:46 +08:00
parent e2f0b5c11a
commit 8f176c1836
5 changed files with 339 additions and 0 deletions
+41
View File
@@ -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}))
}