Tuesday, 20 August 2013

Return elements of the array that form a sum

Return elements of the array that form a sum

I wrote the below code to see if an array has 2 numbers that account to a
sum. I don't know how to capture the elements that contribute to that sum.
Any thoughts
public static boolean isSum(int[] a,int val,int count,int index){
if(count == 0 && val ==0){
return true;
}
if(index>=a.length)
return false;
else{
return
isSum(a,val-a[index],count-1,index+1)||isSum(a,val,count,index+1);
}
}

No comments:

Post a Comment