Recently I came across an algorithmic problem which asks to generate the unique subsets from a given set.
Suppose when the set is
S={1, 2, 3, 4}
where n=4
(number of elements).
then the result should generate all n*(n-1)/2
subsets:- {(1,2),(1,3),(1,4),(2,3),(2,4),(3,4)}
#include<iostream>
int main()
{
int k;
std::cin>>k;
for(long int i=1;i<=k;i++)
{
for(long int j=i+1;j<=k;j++)
{
std::cout<<i<<" "<<j<<"\n";
}
}
return 0;
}
I have an O(n^2) approach but the problem that arising is when the numbers are large for n=1000 it takes lot of time since it had to generate 499,500 elements!
Does anyone has a Better solution complexity wise? algorithm would be appreciated!