Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subset sum variant with modulo

Tags:

Given an array of integers A and integers N, M. I want to find all the subsets S of A where (sum(S) mod M = N). A can have multiple integers of the same value. In my case N will be in the range 0<=n<=31, M will be 32 and A will contain integers in the same range as n.

Is there any good/"fast" way to do this?

Thanks!

like image 462
Anton Andell Avatar asked Dec 19 '17 17:12

Anton Andell


People also ask

Is subset sum NP hard?

SSP can also be regarded as an optimization problem: find a subset whose sum is at most T, and subject to that, as close as possible to T. It is NP-hard, but there are several algorithms that can solve it reasonably quickly in practice.

What is time complexity of subset sum solution using tabulation with N elements and sum's '?

Time Complexity: O(N * sum) where N is the size of the array. Space Complexity: O(N * sum) where N is the size of the array.

What is sum of subset problem give an example?

The SUBSET-SUM problem involves determining whether or not a subset from a list of integers can sum to a target value. For example, consider the list of nums = [1, 2, 3, 4] . If the target = 7 , there are two subsets that achieve this sum: {3, 4} and {1, 2, 4} . If target = 11 , there are no solutions.


1 Answers

It is solvable in O(2n/2 log2(2n/2)) = O(2n/2 (n/2)), with your constrains this works on C++ less than a second.

All you need is:

1) compute all possible sums of first n/2 elements of the array and put them in map<int, int> left where left[sum] = how many times sum appears at the left part of the array

2) compute all possible sums of last n/2 elements of the array and for each sum S check does map left contains value (N - S + M)%M

to find all possible sums you could use bitmasks:

for (int mask = 1; mask < pow(2, n/2); mask++) {
    int sum = 0;
    for (int i = 0; i < n/2; i++)
        if ( (int) (mask & (1<<i)) ) 
            sum += A[i];
}
like image 161
Wsl_F Avatar answered Sep 22 '22 12:09

Wsl_F