Given an array A[n], start by sorting the array.
Then do something like this:
int result[n];
int size=0;
void findSubset(int sum, int position=0)
{
if (sum == 0) output(result, size);
for(int i = position; i < n; ++i)
{
if (A[i] > sum) break;
result[size++] = A[i];
findSubset(i+1, sum-A[i]);
--size;
}
}
Call it like this: findSubset(4);
Don
On Jan 3, 5:26 am, 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.