组合:abc三个字符的所有组合

求所有组合也就是abc各个位是否选取的问题,第一位2中可能,第二位2种。。。所以一共有2^n种。用0表示不取,1表示选取,这样可以用110这样的形式表示ab。abc一共的表示形式从0到2^3-1。然后按位与运算,如果结果为1就输出当前位,结果0不输出。
 

public class Comb {

public static void main(String[] args) {
char[] chs = {'a','b','c'};
comb(chs);
}
 
public static void comb(char[] chs) {
int len = chs.length;
int nbits = 1 << len;
for (int i = 0; i < nbits; ++i) {
int t;
for (int j = 0; j < len; j++) {
t = 1 << j;
if ((t & i) != 0) { // 与运算,同为1时才会是1
System.out.print(chs[j]);
}
}
System.out.println();
}
}
}
来源: https://blog.csdn.net/Tredemere/article/details/52815965

猜你喜欢

转载自www.cnblogs.com/ydcblogs/p/9964329.html