给定一个字符串string A和其长度n,返回所有该字符串所包含字符的各种排列。要求输入字符串长度小于等于11且均为大写英文字符,排列中的字符串按字典序从大到小排序。(重复字符串不用合并)
测试样例:
"ABC"
返回:["CBA","CAB","BCA","BAC","ACB","ABC"]
# -*- coding:utf-8 -*- import itertools class Permutation: # A是一个字符串 def getPermutation(self, A): # write code here res = [] if A == "": return [] lit = list(itertools.permutations(list(A), len(A))) for elem in lit: x = ''.join(elem) if x not in res: res.append(x) res.sort(reverse=True) return res
# -*- coding:utf-8 -*- class Permutation: # A是一个字符串 def getPermutation(self, A): # write code here self.vs=[] self.Permutatio(A,0) result=sorted(self.vs,reverse=True) return result def Permutatio(self,A,i): lena=len(A) #print lena if lena==i: self.vs.append(A) else: for j in range(i,lena): tmp=A[j] trailer=A[j+1:] if j+1<lena else '' A=A[0:j]+A[i]+trailer A=A[0:i]+tmp+A[i+1:] self.Permutatio(A, i+1) tmp=A[j] trailer=A[j+1:] if j+1<lena else '' A=A[0:j]+A[i]+trailer A=A[0:i]+tmp+A[i+1:]