Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我想知道一种可能的算法来计算所有可能的组合,而无需重复,从长度 = 1 开始,直到长度 = N 个元素。
例子:
元素:1、2、3。
输出:
1 2 3 12 13 23 123
查看数字 0 到 2^n - 1 的二进制表示。
n = 3 i Binary Combination CBA 0 000 1 001 A 2 010 B 3 011 A B 4 100 C 5 101 A C 6 110 B C 7 111 A B C
因此,您只需枚举数字 1 到 2^n - 1 并查看二进制表示即可知道要包含哪些元素。如果您想让它们按元素数量排序,则对它们进行排序或按顺序生成数字(SO上有几个示例)。