Given an integer array of size N by the user.
Print all the possible sets such that sum of all possible numbers equate to a number in the array.
Example:
Array A[]= {1,2,3,4,5}
1+2=3..Output:1,2,3
1+3=4..Output:1,3,4
1+4=5..Output:1,4,5
Initial Design:
- Take a number and set it to SetSum
- Generate all sums excluding the selected number; checking that the formulated sum is same as the SetSum
- Print out the numbers that satisfies the conditions above.
- Iterate over the array and set the next number as SetSum
A much efficient Design/Implementation or different approach are welcome..
This problem requires you to find the subsets whose sum totals to a given number(here an element of the set). There are 2 approcahes to doing this:
A brute force algorithm where you generate all the subsets manually and sum them all up which is of exponential order of growth (2^n combinations) or
Use a dynamic programming approach to the problem and find the sum in polynomial time. This is a standard problem in algorithmics called the subset sum problem. If you are not familiar with the concept of dynamic programming, you can look up any algorithms text book. If you understand dynamic programming, then google for the subset sum problem. Hope that helps!