题目描述
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
输入描述:
输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。
itertools.permutations
返回可迭代对象的所有数学全排列方式。
>> from itertools import permutations
>>> permutations(['a', 'b', 'c'])
<itertools.permutations object at 0x7ff7b1411890>
>>> for item in permutations(['a', 'b', 'c']):
... print item
...
('a', 'b', 'c')
('a', 'c', 'b')
('b', 'a', 'c')
('b', 'c', 'a')
('c', 'a', 'b')
('c', 'b', 'a')
map函数
map() 会根据提供的函数对指定序列做映射。
Python 2.x 返回列表。
Python 3.x 返回迭代器。
python set函数
set 和 dict 类似,也是一组 key 的集合,但是不存储 value. 由于 key 不重复,所以,在 set 中, 没有重复的 key 集合是可变类型
#第二种方式创建 set 类型
>>> set2 = set(['z', 'a', 'b', 3, 6, 1])
>>> print(type(set2), set2)
<class 'set'> {1, 3, 6, 'z', 'a', 'b'}
#第三种方式创建 set 类型
>>> set3 = set('hello')
>>> print(type(set3), set3)
<class 'set'> {'o', 'e', 'l', 'h'}
解题代码:
# -*- coding:utf-8 -*-
import itertools
class Solution:
def Permutation(self, ss):
# write code here
if not ss:
return []
return sorted(list(set(map(''.join,itertools.permutations(ss)))))
# -*- coding:utf-8 -*-
class Solution:
def Permutation(self, ss):
if len(ss) <= 1:
return ss
res = set()
# 遍历字符串,固定第一个元素,第一个元素可以取a,b,c...,然后递归求解
for i in range(len(ss)):
for j in self.Permutation(ss[:i] + ss[i+1:]): # 依次固定了元素,其他的全排列(递归求解)
res.add(ss[i] + j) # 集合添加元素的方法add(),集合添加去重(若存在重复字符,排列后会存在相同,如baa,baa)
return sorted(res) # sorted()能对可迭代对象进行排序,结果返回一个新的list