题解 | #字符串的排列#
字符串的排列
https://www.nowcoder.com/practice/fe6b651b66ae47d7acce78ffdd9a96c7
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param str string字符串
# @return string字符串一维数组
#
class Solution:
def Permutation(self, str: str) -> list[str]:
# write code here
path = []
n = len(str)
L2 = list(str)
ans = []
L4 = []
visited = [False for i in range(n)]
#要记得排序。排序了才可以用到那个剪短枝条的公式
L2.sort()
def MyPermutation(L2, L, ans):
if len(L) == n:
ans.append(path.copy())
return
else:
for i in range(len(L2)):
if visited[i]:
continue
if i>0 and L2[i-1]==L2[i] and visited[i-1]==False:
continue
path.append(L2[i])
visited[i] = True
MyPermutation(L2, L, ans)
path.pop()
visited[i] = False
MyPermutation(L2, path, ans)
for x in ans:
L4.append("".join(x))
return L4

