题解 | 字符串的排列
字符串的排列
https://www.nowcoder.com/practice/fe6b651b66ae47d7acce78ffdd9a96c7
package main import "sort" /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param str string字符串 * @return string字符串一维数组 */ func Permutation( str string ) []string { // write code here var tmp []byte used := make([]bool, len(str)) var res []string str = SortStr(str) solve(str, tmp, used, &res) return res } func SortStr(str string) string { runeStr := []byte(str) sort.Slice(runeStr, func(i, j int) bool{ return str[i] < str[j] }) return string(runeStr) } func solve (str string, tmp []byte, used []bool, res *[]string){ if len(tmp) == len(str){ xx := make([]byte, len(tmp)) copy(xx, tmp) *res = append(*res, string(xx)) // *res = append(*res, string(tmp)) return } for i:=0; i<len(str);i++{ if used[i] == true{ continue } if i>0 && str[i] == str[i-1] && used[i-1] == false{ continue } used[i] = true tmp = append(tmp, str[i]) solve(str, tmp, used, res) used[i] = false tmp = tmp[:len(tmp)-1] } }