Count the number of subsets with the sum equal to k

For an array, we need to find out the number of numbers of subsets having a sum exactly equal to a given integer k. Please suggest an optimal algorithm for this problem. Here, the actual subsets are not needed, just the count will do.

An array consists of integers that can be negative as well as non-negative.

Example: Array → {1,4, -1,10,5} abs. Sum-> 9 The answer should be 2 for {4,5} and {-1,10}

+4
source share
2 answers

This is a variation of the problem of summing a subset , which is NP-Hard - so there is no known polynomial solution for it . (In fact, the problem of the sum of the subsets says that it is difficult to find if there is at least one subset that can be summed with a given sum).

Possible approaches to solving it are brute force (check all possible subsets), or if the set contains relatively small integers, you can use the pseudopolynomial dynamic programming method:

f(i,0) = 1    (i >= 0) //succesful base clause
f(0,j) = 0    (j != 0) //non succesful base clause
f(i,j) = f(i-1,j) + f(i-1,j-arr[i])  //step

Applying dynamic programming to the recursive formula above gives you a O(k*n)temporary and spatial solution.

A call with f(n,k)[assuming the index is based on 1 for arrays].

+8

N, N - , 2 ^ n. 0 2 ^ N-1 , i.e . , , , , . , NP, .

-1

Source: https://habr.com/ru/post/1535219/


All Articles