Python程序打印给定字符串的所有排列
排列也称为“排列编号”或“顺序”,是将有序列表 S 的元素重新排列为与 S 本身一一对应的关系。一个长度为 n 的字符串有 n!排列。
来源:Mathword(http://mathworld.wolfram.com/Permutation.html)
下面是字符串ABC 的排列。
ABC ACB BAC BCA CBA CAB
这是一个用作回溯基础的解决方案。
Python3
# Python program to print all permutations
# with duplicates allowed
def toString(List):
return ''.join(List)
# Function to print permutations
# of string
# This function takes three parameters:
# 1. String
# 2. Starting index of the string
# 3. Ending index of the string.
def permute(a, l, r):
if l == r:
print (toString(a))
else:
for i in range(l, r + 1):
a[l], a[i] = a[i], a[l]
permute(a, l + 1, r)
# backtrack
a[l], a[i] = a[i], a[l]
# Driver code
string = "ABC"
n = len(string)
a = list(string)
permute(a, 0, n-1)
# This code is contributed by Bhavya Jain
Python3
# Python program to implement
# the above approach
def permute(s, answer):
if (len(s) == 0):
print(answer, end = " ")
return
for i in range(len(s)):
ch = s[i]
left_substr = s[0:i]
right_substr = s[i + 1:]
rest = left_substr + right_substr
permute(rest, answer + ch)
# Driver Code
answer = ""
s = input("Enter the string : ")
print("All possible strings are : ")
permute(s, answer)
# This code is contributed by Harshit Srivastava
输出:
ABC
ACB
BAC
BCA
CBA
CAB
算法范式:回溯
时间复杂度: O(n*n!) 注意有 n!排列,它需要 O(n) 时间来打印排列。
辅助空间: O(r – l)
注意:如果输入字符串中有重复字符,上述解决方案会打印重复排列。请参阅以下链接以获取即使输入中有重复项也仅打印不同排列的解决方案。
打印具有重复项的给定字符串的所有不同排列。
使用 STL 对给定字符串进行排列
另一种方法:
Python3
# Python program to implement
# the above approach
def permute(s, answer):
if (len(s) == 0):
print(answer, end = " ")
return
for i in range(len(s)):
ch = s[i]
left_substr = s[0:i]
right_substr = s[i + 1:]
rest = left_substr + right_substr
permute(rest, answer + ch)
# Driver Code
answer = ""
s = input("Enter the string : ")
print("All possible strings are : ")
permute(s, answer)
# This code is contributed by Harshit Srivastava
输出:
Enter the string : abc
All possible strings are : abc acb bac bca cab cba
时间复杂度: O(n*n!) 时间复杂度与上述方法相同,即有 n!排列,它需要 O(n) 时间来打印排列。
辅助空间: O(|s|)