简体   繁体   English

子集总和,甚至子集大小

[英]Subset sum but even subset size

So, basically it's the same idea as the subset sum problem, but with one restriction: The found subset needs to have an even size . 因此,基本上,它与子集和问题的想法相同,但有一个限制: 找到的子集需要具有偶数大小

For example: 例如:

numbers {4, 3, 3, 5, 1, 2, 7, 12}
find subset that sums up to 10
=> solution: {4, 3, 1, 2} (or {3, 7} but not {4, 3, 3} )

Is there a simple method to find such a subset? 有没有找到这种子集的简单方法? (The method should be "efficient", not just trying all possible subsets...) (该方法应该是“有效的”,而不仅仅是尝试所有可能的子集...)

Here is my code to find a "normal" subset: 这是我的代码,用于查找“常规”子集:

    int n = 8;
    int m = 11;
    boolean[][] S = new boolean[n][m];
    int[] N = new int[] {4, 3, 3, 5, 1, 2, 7, 12};
    S[0][0] = true;
    S[0][S[0]] = true;

for(int i = 1; i < n; i++) {
        for(int j = 0; j < m; j++) {
            if(N[i] == j) {
                S[i][j] = true;
            } else if(j - N[i] >= 0) {
                S[i][j] = S[i-1][j] || S[i-1][j - N[i]];
            } else {
                S[i][j] = S[i-1][j];
            }
        }
    }

In your current code S[i][j] is true if you can make value j as a subset of numbers up to i. 在当前代码中,如果可以将值j设为最多i的数字子集,则S [i] [j]为true。

Instead, compute S[i][j][k] is true if you can make value j as a subset of numbers up to i with the number of numbers used equal to k modulo 2. 相反,如果您可以将值j作为不超过i的数字的子集,且使用的数字数等于k模2,则计算S [i] [j] [k]为真。

In other words, k is either 0 or 1. 换句话说,k为0或1。

This will require around twice the computations of your existing solution. 这将需要您现有解决方案大约两倍的计算量。

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

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