Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 求数的置换_Java_Python_Algorithm - Fatal编程技术网

Java 求数的置换

Java 求数的置换,java,python,algorithm,Java,Python,Algorithm,我需要一个算法(最好是Java),可以找到一个数字序列的组合。下面是我想要实现的一个例子 假设给定的数字序列是:1 2 3 我希望输出为: 1 2 3 1 3 2 2 1 3 2 3 1 3 1 2 3 2 1 1 2 1 3 2 1 2 3 3 1 3 2 1 2 3 我记得我以前在stackover flow中搜索过这个,我找到了答案,但那是两年前的事了。现在我正在做一个项目,我再次需要那个算法。除非你想重新发明轮子,否则itertools.permutation会满足你的需要 num =

我需要一个算法(最好是Java),可以找到一个数字序列的组合。下面是我想要实现的一个例子

假设给定的数字序列是:1 2 3

我希望输出为:

1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
1 2
1 3
2 1
2 3
3 1
3 2
1
2
3

我记得我以前在stackover flow中搜索过这个,我找到了答案,但那是两年前的事了。现在我正在做一个项目,我再次需要那个算法。

除非你想重新发明轮子,否则itertools.permutation会满足你的需要

num = [1, 2, 3]
from itertools import permutations, chain
perm = chain(*(permutations(num, n) for n in range(len(num),0,-1)))
print '\n'.join(' '.join(map(str,e)) for e in perm)

1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
1 2
1 3
2 1
2 3
3 1
3 2
1
2
3

Python通常被称为“包含电池”,这是有充分理由的

itertools
模块中提供了置换

>>> from itertools import permutations
>>>
>>> l = [1,2,3]
>>> all_permutations = []
>>> for i in range(2, len(l) + 1):
...     all_permutations.extend(list(permutations(l, i)))
...
>>> all_permutations.extend(l)
>>> all_permutations
[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2), (1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1), 1, 2, 3]

您要查找的单词称为
置换
。它的堆很容易用递归函数实现。我知道,我做了很多搜索,但大多数代码示例与我预期的不一样,大多数示例大小固定。powerset………感谢Ankush,“powerset”是正确的关键字:)。我很高兴我又找到了它。@Abu同意它是有教育意义的,但有些东西可能是一次小旅行,可以达到目的。