Java实现全组合

来源:互联网 发布:浙江有多少工厂数据 编辑:程序博客网 时间:2024/06/06 00:59
/** * abs 的all combination is : abc, a, b, c, ab, ac, bc; == 2^n - 1次 */public class Combination {    void combination(String s) {        char[] strs = s.toCharArray();        int n = s.length();        int nbit = 1 << n;        for (int i = 0; i < nbit; i++) {            for (int j = 0; j < n; j++) {                int tmp = 1 << j;                if ((tmp & i) != 0) { // 1&3 == 2, ...                    System.out.print(strs[j]);                }            }            System.out.println();        }        System.out.println("result num is : " + (nbit - 1));    }    public static void main(String[] args) {        new Combination().combination("abc");    }}

参考了网上的博客,主要,就是二进制的理解,还有&的用法,就是两个数, 对于每一位的二进制数,如果两个数都是1, 那么结果中相应位也是1;
比如3的二进制: 0011和 5的二进制: 0101
3 & 3 == 0011 & 0101
== 0011
0101 == 0001 == 1
结果是1

原创粉丝点击