There are 2 ^ n-1 subsets to consider (do not consider the empty set).
On average, each of these 2 ^ n subsets has O (n) elements. So you decide to do n * 2 ^ n calculations to solve the problem.
Some accelerations are possible, but nothing happens around 2 ^ n.
If the absolute size of the elements is small (and discrete), you can run a table indicating whether a particular amount is achievable or not, and adding elements to these “locations” in your table.
Make a table first. This range will be from the sum of all negative numbers to the sum of all positive numbers. (This way you won’t get any amounts outside the table.)
Then mark "0" available.
Then, for each number, for each available number in your table, add a number. Therefore, if your first number is 2, then mark “2” as reachable. Then, if you get -3, mark "-3" and "2-3 = -1" as achievable. And so on, until you finish the numbers. Each part of the table designated as achievable is truly achievable; You added some numbers to get there!
source share