找到数字的排列

时间:2013-01-10 05:41:28

标签: 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流程中搜索了这个,我找到了答案,但就像2年前一样。现在我正在做一个项目,我又需要那个算法。

2 个答案:

答案 0 :(得分:2)

除非你想重新发明轮子,否则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

答案 1 :(得分:2)

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

permutations位于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]