Project Euler 24 Lexicographic permutations

Question

A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are:

012 021 102 120 201 210

What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?

Analysis

  1. n个数全排列共有n\,!种排列方式。本题中,如果第一个数确定了,则有9\,!种可能排列结果。那么,第m\,(m<9\,!)个排列的第一个数字必然是0。
  2. 1000000\,//\,9\,!=2,所以第1000000个排列的第一个数字是2。
  3. 题目转换为,求数字0,1,3,4,5,6,7,8,9组成的排列中第1000000-2\times9\,!个排列是多少。如此递归下去即可得到结果。
  4. 关于为什么要 - 1,很难解释清楚,但是根据推理很容易得到。10个数字组成的第一个排列应该是 0123456789,如果不减1,带入到代码中得到的会是 0123456798。

Program

number_order = 1000000
length = 10

max_factor = 3628800  # the factorial of 10
num_list = list(range(length))
rst = []

number_order -= 1
while len(num_list) > 0:
    max_factor //= len(num_list)
    integer = number_order // max_factor
    rst.append(num_list.pop(integer))
    number_order %= max_factor

print(rst)
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 8,137评论 0赞 10
  • Lua 5.1 参考手册 by Roberto Ierusalimschy, Luiz Henrique de F...
    苏黎九歌阅读 14,383评论 0赞 38
  • 对自己展开思考,通过“基本”方法(目标➡️计划➡️习惯➡️实践、模仿...)成为自己。 “100个基本...
    蓝water阅读 205评论 0赞 1
  • 不知道各位是否有过这样的经历——— 每每看到学习平台发布的线上课程,里面的文案,句句戳中你的内心,激起你想要学习的...
    罗沫沫66阅读 977评论 0赞 3
  • 春节是中国传统而喜庆的节日,过年就是一家男男女女老老少少合家团圆,我现在就跟大家来说说我的年味。 春节是除旧...
    肖俊榆阅读 480评论 0赞 1

友情链接更多精彩内容