题解 | #字符串的排列#
字符串的排列
http://www.nowcoder.com/practice/fe6b651b66ae47d7acce78ffdd9a96c7
import "sort"
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* @param str string字符串
* @return string字符串一维数组
*/
func Permutation( str string ) []string {
t := []byte(str)
sort.Slice(t, func(i, j int) bool {
return t[i] < t[j]
})
n := len(t)
ans := []string{}
cur := make([]byte, 0 , n)
vis := make([]bool, n)
var backtrack func(int)
backtrack = func(i int) {
if i == n {
ans = append(ans, string(cur))
return
}
for j, b := range vis {
if b || j > 0 && !vis[j-1] && t[j-1] == t[j] {
continue
}
vis[j] = true
cur = append(cur, t[j])
backtrack(i+1)
cur = cur[:len(cur) - 1]
vis[j] = false
}
}
backtrack(0)
return ans
}