sorry a lil bit modification in the above answer..
*int ref[] = {1,2,3};*
*void printcombination(int n,int index,int i)*
*{*
*static int a[100];*
*int j;*
*if (n == 0)*
* {*
* for(j=0;jindex;j++)*
*
Given an array and a sum S output all combinations of elements that
sum to S.
eg: 1 2 3
sum = 3
1+1+1,
2+1
3
I came up with the foll algorithm, but it outputs 2+1 and 1+2 again.
(does not handle repetitions)
printcombinations(int a[],int sum,int level) {
if(sum==0) { print array}
else if (sum0)
pass one more argument to the function *int index* and instead of starting
the loop from *i = 0 to N, *make it start from *i = index to N *and then
call
*printcombinations(a,sum-a[i],level+1,index+1);
*I think it will work then...
On Thu, Jun 23, 2011 at 10:48 AM, ross