[英]How to find sum of the elements in the Subsets
我想找到其元素可被2整除或元素之和可被2整除的子集数量
我找到了给定数组的所有可能子集
for(int i=1;i<=(Math.pow(2,n));i++) //Loop for all 2^n combinations
{
for(int j=0;j<n;j++)
{
if((i&(1<<j))>0) //This gives the subset of the array
输入:1 2 3输出:3作为{2},{1,3 = 4},{1,2,3 = 6}是可以被2整除或其元素之和可以被2整除的子集。
在此假设下:
n
(自然数) ...(准确的)结果是:
分别(=):
分别(=):
O(log(n))
算法:
public class Test {
public static long countSuperClever(int n) {
return pow(2L, (long) n - 1) - 1L;
}
// best thx to https://codingforspeed.com/using-faster-integer-power-in-java/
private static long pow(long a, long b) {
long re = 1L;
while (b > 0) {
if ((b & 1) == 1) {
re *= a;
}
b >>= 1;
a *= a;
}
return re;
}
public static void main(String[] args) {
for (int i = 3; i < 12; i++) {
System.out.println(countSuperClever(i));
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.