问题描述:
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
输入描述:
输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。
解题思路:
回溯法
# -*- coding:utf-8 -*-
class Solution:
def Permutation(self, ss):
# write code here
slist = list(ss)
plist = self.permute(slist, 0)
plist = list(set(plist))
plist.sort()
return plist
def permute(self, ss, pBegin):
p = []
if pBegin == len(ss) - 1:
return [ss[pBegin]]
for i in range(pBegin, len(ss)):
ss[pBegin], ss[i] = ss[i], ss[pBegin]
tmp = [ss[pBegin] + c for c in self.permute(ss, pBegin+1)]
p.extend(tmp)
ss[pBegin], ss[i] = ss[i], ss[pBegin]
return p
或者对下标进行去全排:
# -*- coding:utf-8 -*-
class Solution:
def Permutation(self, ss):
# write code here
sslist = list(ss)
permutelist = []
if sslist == []:
return permutelist
self.getpermute(sslist, permutelist, [])
permutelist = list(set(permutelist))
permutelist.sort()
return permutelist
def getpermute(self, slist, plist, per):
if len(slist) == len(per):
plist.append(''.join([slist[i] for i in per]))
return
for ind in range(len(slist)):
if ind not in per:
per.append(ind)
self.getpermute(slist,plist,per)
per.remove(ind)