If you have an O(n^2) algorithm, you will be famous because you will have proven that P=NP. As has been pointed out, this is the subset sum problem, well known to be NP hard.
It is only "weakly" NP hard, though. There is a simple pseudo- polynomial time DP algorithm. Let S(n, k) be a boolean function true iff there is a subset of elements that sum to n using only elements 1,2,...,k. Then S(n,k) = S(n,k-1) or S(n - a[k], k-1) for n,k>0. The base cases are S(0,k)=true for k>=0 and S(n,0)= false for n>0. The intuition here is "you either skip usiong the k'th item in the subset or use it." This just tells you whether a subset exists. It's easy to find the subset elements with back pointers in the DP table, which will form a tree rooted at S(n, N) where the array has N elements. Each root-leaf path in the tree will be a valid subset. This algorithm is polynomial in the _size_ of the elements, which is exponential time by the normal definition, but can be useful if data are small. That's why it's called pseudo-polynomial time. On Jan 3, 12:26 pm, atul anand <[email protected]> wrote: > There is integer array like {1,2,4,5,6,1,2,4,3,5,7,2,1}. I want to find the > possible combination which will sum to 4. > input : {1,2,4,5,6,1,2,4,3,5,7,2,1} > output : {1,1,2}, {2,2}, {3,1}, {1,2,1}{4}...etc which make the sum as 4 > > any approach better than O(n^2) ??? -- You received this message because you are subscribed to the Google Groups "Algorithm Geeks" group. To post to this group, send email to [email protected]. To unsubscribe from this group, send email to [email protected]. For more options, visit this group at http://groups.google.com/group/algogeeks?hl=en.
