输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串 abc,则打印出由字符 a, b, c 所能排列出来的所有字符串 abc, acb, bac, bca, cab 和 cba。
输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。
解题思路
排列组合迭代器
迭代器 | 实参 | 结果 |
---|---|---|
product() | p, q, … [repeat=1] | 笛卡尔积,相当于嵌套的for循环 |
permutations() | p[, r] | 长度r元组,所有可能的排列,无重复元素 |
combinations() | p, r | 长度r元组,有序,无重复元素 |
combinations_with_replacement() | p, r | 长度r元组,有序,元素可重复 |
product('ABCD', repeat=2) | AA AB AC AD BA BB BC BD CA CB CC CD DA DB DCDD | |
permutations('ABCD', 2) | AB AC AD BA BC BD CA CB CD DA DB DC | |
combinations('ABCD', 2) | AB AC AD BC BD CD | |
combinations_with_replacement('ABCD',2) | AA AB AC AD BB BC BD CC CD DD |
itertools.permutations(iterable, r=None)
连续返回由 iterable 元素生成长度为 r 的排列。
如果 r 未指定或为 None
,r 默认设置为 iterable 的长度,这种情况下,生成所有全长排列。
排列依字典序发出。因此,如果 iterable 是已排序的,排列元组将有序地产出。
即使元素的值相同,不同位置的元素也被认为是不同的。如果元素值都不同,每个排列中的元素值不会重复
import itertools
class Solution:
def Permutation(self, ss):
# write code here
if not ss:
return []
return sorted(list(set(map(''.join, itertools.permutations(ss)))))