简体   繁体   English

查找大小大于或等于2的数组的所有子集

[英]find all subsets of array having subset of size greater than or equal to 2

The below code prints all subsets, but I need of size greater than or equal to 2. 下面的代码打印所有子集,但是我需要大于或等于2的大小。

public static void printSubsets(char set[])
{
    int n = set.length;

    for (int i = 0; i < (1<<n); i++)
    {
        System.out.print("{ ");

        for (int j = 0; j < n; j++)

            if ((i & (1 << j)) >0 )
                System.out.print(set[j] + " ");

        System.out.println("}");
    }
}

A subset of size 0 corresponds to i == 0 . 大小为0的子集对应于i == 0 To eliminate the empty subset start at i = 1 . 要消除空子集,请从i = 1开始。

A subset of size 1 corresponds to i having exactly one bit set; 大小为1的子集对应于i刚好设置了一位; or, equivalently, when it is a power of 2. A positive number i is a power of two if (i & (i - 1)) == 0 . 或等效地,当它是2 的幂时,如果(i & (i - 1)) == 0 则正数i是2的幂

for (int i = 1; i < (1<<n); i++) {
    if ((i & (i - 1)) == 0) {
        continue;
    }

    System.out.print("{ ");

    for (int j = 0; j < n; j++) {
        if ((i & (1 << j)) != 0) {
            System.out.print(set[j] + " ");
        }
    }

    System.out.println("}");
}

Alternatively, you could keep your original loop and simply insert this check: 另外,您可以保留原始循环,然后简单地插入以下检查:

if (Integer.bitCount(i) < 2) {
    continue;
}

It's not as clever or efficient, but it is nice and readable. 它不那么聪明或高效,但是很好看并且可读。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 查找第一个元素大于或等于最后一个元素且子数组大小等于 X 的子数组 - Find subarrays with first element greater than or equal to last element and the subarray size equal to X 如何查找数组中包含相等总和的子集: - How to find subsets that contains equal sum in an array: MongoTemplate 查询以查找子数组大小大于 - MongoTemplate Query to find Objects with child array size greater than subset sum查找所有加起来的子集 - subset sum find all subsets that add up to a number 与数据结构有关。 查找所有大于或等于给定输入的数组元素 - Datastructure related. Find all arrays elements greater than or equal to given input 给定整数数组,找到所有“最大”子集 - Given an array of integers find all “maximal” subsets 给定一个整数N和一个整数G,找到GCD大于G的所有元素对&lt;= N - Given an interger N and an integer G, find all pairs of element <=N having GCD greater than G 打印出一个递归等于给定和的数组中的所有子集 - Print out all subsets in an array that equal an given sum recursively 回溯并找到等于某个值k的所有数组子集 - Backtracking and finding all subsets of array that equal some value k 递归打印数组中等于给定总和的所有子集 - Print all subsets in an array that equal to a given sum recursively
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM