程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

2023-05(1)

2023-06(2)

【Python】递归实现n的全排列

发布于2019-08-05 18:54     阅读(1107)     评论(0)     点赞(1)     收藏(3)


这是面试字节跳动的大数据岗位时候面试官给的一个题目,就是输出n个数的全排列。

当n=1是,perm(1)= [[1]]

当n=2是,对于perm(1)里面的每个子list,n可以在list的第0个位置到最后一个位置,这里perm(1)里只有一个子list [1],所以perm(2)= [[2,1],[1,2]]

当n=3时,perm(2)的子list有[2,1]和[1,2],
对于子list为[2,1],3可以插入到[2,1]的第0个位置,到第二个位置,分别为[3,2,1],[2,3,1],[2,1,3],同样对于子list为[1,2]时,可以得到[3,1,2],[1,3,2],[1,2,3]
得到perm(3)=[[3,2,1],[2,3,1],[2,1,3],[3,1,2],[1,3,2],[1,2,3]]

因此对于perm(n)来说,先取perm(n-1)的每个子列表,然后依次在每个子列表中的每个位置插入n,即可得到perm(n)。

代码示例:

import copy

def perm(n):
    data = []
    if(n == 1):
        data.append([1])
    else:
        for m in pai(n-1):
            for j in range(len(m)+1):
                k = copy.copy(m)#浅拷贝
                k.insert(j,n)
                data.append(k)
    return data
perm(4)

结果:
[[4, 3, 2, 1],
[3, 4, 2, 1],
[3, 2, 4, 1],
[3, 2, 1, 4],
[4, 2, 3, 1],
[2, 4, 3, 1],
[2, 3, 4, 1],
[2, 3, 1, 4],
[4, 2, 1, 3],
[2, 4, 1, 3],
[2, 1, 4, 3],
[2, 1, 3, 4],
[4, 3, 1, 2],
[3, 4, 1, 2],
[3, 1, 4, 2],
[3, 1, 2, 4],
[4, 1, 3, 2],
[1, 4, 3, 2],
[1, 3, 4, 2],
[1, 3, 2, 4],
[4, 1, 2, 3],
[1, 4, 2, 3],
[1, 2, 4, 3],
[1, 2, 3, 4]]



所属网站分类: 技术文章 > 博客

作者:heer

链接:https://www.pythonheidong.com/blog/article/6603/d9af92e53393b6000dfd/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

1 0
收藏该文
已收藏

评论内容:(最多支持255个字符)