给定字符串S[0…N-1],枚举S的全排列
直接使用itertools的工具
from itertools import permutations
a=['a','b','c','d']
for p in permutations(a):
print(p)
递归算法
def permutation(str,start,end):
if(start==end):
for s in str:
print(s,end='')
print('')
return
for i in range(start,end+1):
str[start],str[i]=str[i],str[start]
permutation(str,start+1,end)
str[start], str[i] = str[i], str[start]
a=[1,2,3,4]
permutation(a,0,len(a)-1)
有重复字符
交换数据时,先查询区间内(两个交换字符的区间)是否有重复字符,如果有则跳过
def permutation(str,start,end):
if(start==end):
for s in str:
print(s,end='')
print('')
return
for i in range(start,end+1):
if not isrepeat(str,start,i):
continue
str[start],str[i]=str[i],str[start]
permutation(str,start+1,end)
str[start], str[i] = str[i], str[start]
def isrepeat(str,start,i):
bcan=True
#第i个字符与第j个字符交换时,要求[i,j)中没有与第j个字符相等的数
for j in range(start, i):
if str[start]==str[i]:
bcan=False
break
return bcan
a=[1,2,3,4,4]
permutation(a,0,len(a)-1)