【PTA】【浙大版《Python 程序设计》题目集】第6章-8 *6-7 输出全排列 (20 分)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_43733499/article/details/102722747

输出全排列

请编写程序输出前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)

猜你喜欢

转载自blog.csdn.net/qq_43733499/article/details/102722747