输入只有一行,是一个由不同的小写字母组成的字符串,已知字符串的长度在1到6之间。
输出这个字符串的所有排列方式,每行一个排列。要求字母序比较小的排列在前面。字母序如下定义: 已知S = s1s2...sk , T = t1t2...tk,则S < T 等价于,存在p (1 <= p <= k),使得 s1 = t1, s2 = t2, ..., sp - 1 = tp - 1, sp < tp成立。 每组样例输出结束后要再输出一个回车。
abc
abc acb bac bca cab cba
def dfs(p):
if p==lenth:
res.append(''.join(temp))
return
else:
for i in range(lenth):
if visit[i]:
temp[p]=arr[i]
visit[i]=False
dfs(p+1)
visit[i]=True
while True:
try:
arr=input().strip()
lenth=len(arr)
temp=['']*lenth
visit=[True]*lenth
res=[]
dfs(0)
res=sorted(res)
for i in res:
print(i)
print()
except:
break
#通过递归交换数组,得到一个无重复列表的全排列
#需要注意几点,输入字母未排序,输出最后还要加一个空格(应该是利于某些算法)
#这函数输入如果是有序的可以得到按顺序的全排列
def allPermute(array):
result = []
tempArray = list(array)
def exchange(num):
nonlocal tempArray
nonlocal result
if num == len(tempArray)-1:
result.append(list(tempArray))
else:
for j in range(num,len(tempArray)):
tempArray[num],tempArray[j] = tempArray[j],tempArray[num]
exchange(num+1)
tempArray[num], tempArray[j] = tempArray[j], tempArray[num]
exchange(0)
return result
try:
while True:
string = list(input())
temp = allPermute(string)
temp.sort()
for i in temp:
print("".join(i))
print()
except Exception:
pass 谁能解释一下,为什么这种解法可以通过:
from itertools import permutations
while True:
try:
a = list(permutations(sorted(input())))
b = len(a)
for i in range(b - 1):
print(''.join(a[i]))
print(''.join(a[- 1]) + '\n')
except:break
而这种却通不过?
from itertools import permutations
while True:
try:
for i in permutations(input()):
print("".join(i))
print("\n")
except:break
真是****一样的判定系统。