枚举数组的所有子集

发布时间 2023-08-01 16:57:57作者: r1-12king

参考:

 

https://blog.csdn.net/weixin_43212830/article/details/122756392

 

https://blog.csdn.net/qq_34261446/article/details/103522369

 

 

/**
 * @description: ,枚举数组的所有子集
 * @author: luguilin
 * @date: 2023-08-01 16:22
 **/
public class EnumAllSet {

    public static void test(int x, int [] nums){
        for(int i = x;i!=0;i = ((i - 1) & x)){
            int n = nums.length;
            List<Integer> res = new ArrayList<>();
            for(int j=0; j<n; j++){
                //二进制下某一位为1,则表示这一位所代表的数组被使用
                if((i & (1<<j)) !=0){
                    res.add(nums[j]);
                }
            }
            for (Integer re : res) {
                System.out.print(re+" ");
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        test(7,new int[]{1,2,3});
    }
}