题目描述
输入一个字符串,按字典序打印出该字符串中字符的所有排列。
Leetcode有类似的题
样例
例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
想法一:
使用itertools库中的permutations方法直接通过字符串构造全排列组合,然后使用set去重后转list再排序
# 直接使用itertools中的permutations方法对元素全排列
class Solution:
def Permutation(self, ss):
res = []
for i in itertools.permutations(ss):
if ''.join(i) not in res:
res.append(''.join(i))
return res
想法二:
递归遍历,
# 递归遍历
class Solution:
def Permutation(self, ss):
if not ss:
return []
res = []
self.fun(ss, res, '')
return sorted(list(set(res)))
def fun(self, ss, res, string):
if not ss:
res.append(string)
for i in range(len(ss)):
self.fun(ss[:i] + ss[i + 1:], res, string + ss[i])
最后
刷过的LeetCode或剑指offer源码放在Github上了,希望喜欢或者觉得有用的朋友点个star或者follow。
有任何问题可以在下面评论或者通过私信或联系方式找我。
联系方式
QQ:791034063
Wechat:liuyuhang791034063
CSDN:https://blog.csdn.net/Sun_White_Boy
Github:https://github.com/liuyuhang791034063