字符串全排列python实现

给定字符串S[0…N-1],枚举S的全排列

算法1

直接使用itertools的工具


from itertools import permutations

a=['a','b','c','d']
for p in permutations(a):
    print(p)

算法2

递归算法


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)

算法3

有重复字符

交换数据时,先查询区间内(两个交换字符的区间)是否有重复字符,如果有则跳过


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)
©️2020 CSDN 皮肤主题: 点我我会动 设计师:上身试试 返回首页