| Write a function that takes an... | |||||||
|
30 Day Risk-Free Guarantee:
100% money back if you're unsatisfied. Book (308 Pages):
![]() Video (One Hour):
![]() Resume Review (24 - 48hr)
All Products / Services
|
|||||||
Write a function that takes an array of five integers, each of which is between 1 and 10, and returns the number of combinations of those integers that sum to 15. For example, calling the function with the array [1, 2, 3, 4, 5] should return 1, while calling it with [5, 5, 10, 2, 3] should return 4 (5 + 10, 5 + 10, 5 + 5 + 2 + 3, 10 + 2 + 3). You may assume that the input has already been validated. Show how you would test this function
Asking help to provide both recursive and non-recursive solution.
7
Dynamic programming just gives a yes and no answer....how do you get it in O(n2) by DP?
How about this: non-recursive O(n^2)
int FindSumCount(int arr[], int n)
{
int sum=0;
int count=0;for(int i=0;i<n;i++)
{
sum=0;
for(int j=i;j<n;j++)
{
sum += arr[j];if(sum == 15)
count++;
else if(sum<15)
continue;
sum -= arr[j];
}
}
return count;
}
for [5, 5, 10, 2, 3] your function returns 3 not 4
// Here is recursive one
static int total=0;
void FindSumCombo(int *, int, int, int);
const int ALLSUM=15;
int _tmain(int argc, _TCHAR* argv[])
{
int* arr = new int[argc-1];
for(int i=1;i<argc;i++)
{
arr[i-1]=_ttoi(argv[i]);
}for(int i=0;i<5;i++)
FindSumCombo(arr,0,i,4);
std::cout<<total;
return 0;
}void FindSumCombo(int* arr, int sum, int start, int end)
{
if(start==end)
{
if(arr[start]+sum==ALLSUM)
{
total++;
return;
}
else
{
return;
}
}
if(arr[start]+sum==ALLSUM)
{
total++;
FindSumCombo(arr,sum,1+start,end);
}
if(arr[start]+sum>ALLSUM)
{
FindSumCombo(arr,sum,1+start,end);
}
if(arr[start]+sum<ALLSUM)
{
FindSumCombo(arr,sum+arr[start],start+1,end);
}
return;}
I think;
Recursive -> O(2^n)
Non-Recursive (Dynamic programming) -> O(n^2)