[英]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.