Given an array of integers and a unique number. Find all different combination of numbers from the array that add up to the unique number. Print all possible combination.
Hint: Use Dynamic Programming
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
const int size=30;
void main()
{
clrscr();
randomize();
int a[size],unique,k=0;
cout<<"Elements of array are:\n";
for(int i=0;i<size;i++)
{
a[i]=10+random(90); //random numbers between 10-99//
cout<<a[i]<<" ";
}
unique=300+random(500); //unique number between 300-799//
cout<<"\nUnique number is: "<<unique;
cout<<"\nDifferent combinations are:\n";
for(int i=0;i<size;i++)
{
for(int j=i+1;j<size;j++)
{
if((a[i]+a[j])==unique)
{
cout<<a[i]<<" + "<<a[j]<<" = "<<unique<<"\n";
}
else
{
k=j+1;
int temp=0;
while(k<size)
{
temp+=a[k];
if((a[i]+a[j]+temp)==unique)
{
int l=k;
cout<<a[i]<<" + "<<a[j];
while(l>=j+1)
{
cout<<" + "<<a[l];
l--;
}
cout<<" = "<<unique<<"\n";
}
k++;
}
}
}
}
getch();
}
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks