给定一个整数数组 [x0 x1 x2],如何计算从 [0 0 0] 到 [x0 x1 x2] 的所有可能排列?
我正在编写一个接受 ArrayList 的程序,我需要计算所有可能的排列,从零列表开始,直到相应输入列表中的值。
有谁知道如何迭代计算这些值?
例如,给定 [ 1 2 ] 作为输入,它应该查找并存储以下列表:
[0 0], [1 0], [1 1], [1 2], [0 1], [0 2]
谢谢!
I am writing a program that takes in an ArrayList and I need to calculate all possible permutations starting with a list of zeroes, up to the value in the corresponding input list.
Does anyone know how to iteratively calculate these values?
For example, given [ 1 2 ] as input, it should find and store the following lists:
[0 0],
[1 0],
[1 1],
[1 2],
[0 1],
[0 2]
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一个标准的递归生成器:
它的工作方式与编写可变数量的嵌套循环相同。使用递归,您只需要编写一个循环,并且它实际上可以具有可变的嵌套深度(如果您不小心,则可以是无限的!)。
还有迭代即非递归版本:
这与二进制算术(或任何基数,实际上)中加 1 的工作方式大致相同,只是每个位置都有其自己的限制。
例如,以 10 为基数,递增方式如下:
Here's a standard recursive generator:
This works in the same way as if you've had written variable number of nested loops. With recursion, you only have to write one loop, and it can actually have variable nesting depth (infinite if you're not careful!).
There's also the iterative i.e. non-recursive version:
This works in much the same way that increment by 1 works in binary arithmetic (or any base, really), except each position has its own limit.
For example, in base 10, here's how you increment:
看起来您实际上并不想要排列。如果给定一个数组 X = [1, 2],它的排列恰好是 [1, 2] 和 [2, 1]。根据您的示例,您希望它生成所有元组 z,其中 0 <= z <= X。polygenelubricants
的解决方案很好地解决了这个元组列表问题。 Fazal 的解决方案解决了您所说的排列问题。
It doesn't look like you actually want permutations. If you are given an array X = [1, 2], its permutations are exactly [1, 2] and [2, 1]. Going by your example, you want it to generate all tuples z where 0 <= z <= X.
This tuple-listing problem is nicely solved by polygenelubricants's solution. Your stated permutation problem is solved by Fazal's solution.