数组组合数输出

本文介绍了一种利用二进制表示和位运算快速生成数组所有组合的方法,通过实例代码展示了如何从字符数组中生成所有可能的组合,包括单个元素、两两组合直至所有元素的组合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近看了一个题,就是输出数组中所有的组合情况(不需考虑元素重复)

对于这个问题,我花了大概15分钟思考了下,时间还是比较长的。

我的思路如下。

1.比如字符数组为char c[]={'a','b','c'},那么输出的情况为a,b,c,ab,ac,bc,abc。

2.那么针对于上面的情况那就是真值表嘛,100,010,001,110,101,011,111.

3.那么解法也就相当简单了,将一个数从0到全1增加,并输出对应为1时的那个字符,那么组合数便得出了。

很简单吧!具体代码如下,我用的java:

class Assemb {
	char c[];//预组合数组
	int n[];//标志区

	public Assemb(char[] c) {
		this.c = c;
		n = new int[c.length];
	}

	public boolean isFull() {//检测全1
		for (int i = 0; i < n.length; i++) {
			if (n[i] == 0) {
				return false;
				}
		}
		return true;
	}
	public void getResult() {//结果输出
		while (!isFull()) {
			add();
			print();
		}
	}
	public void add() {//增加 比如00->001
		n[n.length - 1]++;
		for (int i = n.length - 1; i >= 0; i--) {
			if (n[i] == 2) {
				n[i] = 0;
				if (i - 1 >= 0){
					n[i - 1]++;
				}
				else{
					n[i - 1]=0;
				}
			}
		}
	}

	public void print() {//输出有1标志的
		for (int i = 0; i < n.length; i++) {
			if (n[i] == 1) {
				System.out.print(c[i]);
			}
		}
		System.out.println();
	}
}
Assemb a=new Assemb(new char[]{'a','b','c','d','e','f','g','h'});//即可得到输出的组合结果

本次结果如下:
h
g
gh
f
fh
fg
fgh
e
eh
eg
egh
ef
efh
efg
efgh
d
dh
dg
dgh
df
dfh
dfg
dfgh
de
deh
deg
degh
def
defh
defg
defgh
c
ch
cg
cgh
cf
cfh
cfg
cfgh
ce
ceh
ceg
cegh
cef
cefh
cefg
cefgh
cd
cdh
cdg
cdgh
cdf
cdfh
cdfg
cdfgh
cde
cdeh
cdeg
cdegh
cdef
cdefh
cdefg
cdefgh
b
bh
bg
bgh
bf
bfh
bfg
bfgh
be
beh
beg
begh
bef
befh
befg
befgh
bd
bdh
bdg
bdgh
bdf
bdfh
bdfg
bdfgh
bde
bdeh
bdeg
bdegh
bdef
bdefh
bdefg
bdefgh
bc
bch
bcg
bcgh
bcf
bcfh
bcfg
bcfgh
bce
bceh
bceg
bcegh
bcef
bcefh
bcefg
bcefgh
bcd
bcdh
bcdg
bcdgh
bcdf
bcdfh
bcdfg
bcdfgh
bcde
bcdeh
bcdeg
bcdegh
bcdef
bcdefh
bcdefg
bcdefgh
a
ah
ag
agh
af
afh
afg
afgh
ae
aeh
aeg
aegh
aef
aefh
aefg
aefgh
ad
adh
adg
adgh
adf
adfh
adfg
adfgh
ade
adeh
adeg
adegh
adef
adefh
adefg
adefgh
ac
ach
acg
acgh
acf
acfh
acfg
acfgh
ace
aceh
aceg
acegh
acef
acefh
acefg
acefgh
acd
acdh
acdg
acdgh
acdf
acdfh
acdfg
acdfgh
acde
acdeh
acdeg
acdegh
acdef
acdefh
acdefg
acdefgh
ab
abh
abg
abgh
abf
abfh
abfg
abfgh
abe
abeh
abeg
abegh
abef
abefh
abefg
abefgh
abd
abdh
abdg
abdgh
abdf
abdfh
abdfg
abdfgh
abde
abdeh
abdeg
abdegh
abdef
abdefh
abdefg
abdefgh
abc
abch
abcg
abcgh
abcf
abcfh
abcfg
abcfgh
abce
abceh
abceg
abcegh
abcef
abcefh
abcefg
abcefgh
abcd
abcdh
abcdg
abcdgh
abcdf
abcdfh
abcdfg
abcdfgh
abcde
abcdeh
abcdeg
abcdegh
abcdef
abcdefh
abcdefg
abcdefgh


希望我的思路能给大家对于编程的奥秘带个头,希望大家可以互相交流,共同进步。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值