您希望组合按长度顺序排列。在 Python 中你可以这样写:
import itertools
def subsets(iterable):
"Generate the subsets of elements in the iterable, in order by length."
items = list(iterable)
for k in xrange(len(items) + 1):
for subset in itertools.combinations(items, k):
yield subset
>>> list(subsets([1,2,3,4]))
[(), (1,), (2,), (3,), (4,), (1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4),
(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4), (1, 2, 3, 4)]
See 这个答案 https://stackoverflow.com/questions/127704/algorithm-to-return-all-combinations-of-k-elements-from-n/127856#127856了解生成组合的算法的概述。 (或者你可以看看 Raymond Hettinger 的 Python 实现,itertools module.c 行 2026f http://hg.python.org/cpython/file/9a0b6c07b488/Modules/itertoolsmodule.c#l2026.)