元素的所有可能组合 [英] All possible combinations of elements

查看:52
本文介绍了元素的所有可能组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道一种可能的算法,该算法可以计算长度从N个元素的N个元素开始直到N个元素的N个元素。

I'd like to know a possible algorithm to calculate all possible combinations, without repetitions, starting from length=1 until length=N of N elements.

示例:

元素:1、2、3。

输出:


1
2
3
12
13
23
123


推荐答案

看看数字0到2 ^ n-1的二进制表示形式。

Look at the binary presentation of the numbers 0 to 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上有多个示例)。

So you just have to enumerate the numbers 1 to 2^n - 1 and look at the binary representation to know which elements to include. If you want to have them ordered by the number of elements post sort them or generate the numbers in order (there are several example on SO).

这篇关于元素的所有可能组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆