剑指 Offer 38. 字符串的排列

image-20220309125700035

将字符 c[i]c[x] 交换,即固定 c[i] 为当前位字符;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
func permutation(s string) []string {
var res []string
combinations(nil,0,[]byte(s),&res)
return res
}
func combinations(current []byte, index int,src []byte, res *[]string){
var encountered = make(map[byte]struct{},0)
if index >= len(src){
*res = append(*res,string(current))
return
}
for i:=index ; i<len(src); i++{
if _,ok := encountered[src[i]];ok{
continue
}
currentByte := src[i]
encountered[currentByte] = struct{}{}
src[i],src[index] = src[index],src[i]

current = append(current,currentByte)
combinations(current,index+1,src,res)

src[i],src[index] = src[index],src[i]
current = current[:len(current)-1]
}
return
}