繁体   English   中英

如何在子集中找到元素的总和

[英]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 (自然数)
  • 输出是“偶数子集”的计数(大小为n的自然数序列)

...(准确的)结果是:

sum(binomial(n-1,k),[1 .. n-1]中的k)

分别(=):

floor(sum(binomial(n,k),k in [1 .. n])/ 2)

分别(=):

(2 ^(n-1))-1


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));
        }
    }

}

另请参阅: https : //math.stackexchange.com/a/1338830/20447

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM