版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
输出全排列
请编写程序输出前n个正整数的全排列(3<=n<=7),按字典序输出。
输入格式:
一行输入正整数n。
输出格式:
按字典序输出1到n的全排列。每种排列占一行,数字间无空格。
输入样例:
在这里给出一组输入。例如:
3
输出样例:
在这里给出相应的输出。例如:
123
132
213
231
312
321
思路:
写个全排列函数。
代码如下:
def permutations(n):
indices = list(range(1,n+1))
for i in range(0,n):
print(indices[i],end="")
print("")
while True:
low_index = n-1
while low_index > 0 and indices[low_index-1] > indices[low_index]:
low_index -= 1
if low_index == 0:
break
low_index -= 1
high_index = low_index+1
while high_index < n and indices[high_index] > indices[low_index]:
high_index += 1
high_index -= 1
indices[low_index], indices[high_index] = indices[
high_index], indices[low_index]
indices[low_index+1:] = reversed(indices[low_index+1:])
for i in range(0, n):
print(indices[i], end="")
print("")
n=int(input())
permutations(n)