0

I am a novice programmer and very weak in complexity calculation. I have learnt to write a program for creating all possible subsets from a set of elements, i.e. knapsack algorithm. Now I would like to know how to calculate the complexity of the algorithm. Can anyone help me with better clarification. Here is my code:

#include<iostream>
#include<cstdio>
#include<map>
#include<vector>
using namespace std;
int N,M,a[15];
map<int,vector<int> >multiple;
void creating_subset(int i,int m,int l)
{
  if(i>=M)
  {
    multiple[l].push_back(m);
    return;
  }
  creating_subset(i+1,m*a[i],l+1);
  creating_subset(i+1,m,l);
}
int main()
{
  cin>>M;
  for(int i=0;i<M;i++)
  cin>>a[i];
  creating_subset(0,1,0);
  for(int i=0;i<multiple[3].size();i++)
  printf("%d ",multiple[3][i]);
  cout<<endl;
  return 0;
}
Yuval Filmus
  • 280,205
  • 27
  • 317
  • 514

1 Answers1

1

Your code doesn't really generate all subsets, but it does go over all subsets. The complexity of your code depends on the complexity of the data structures you use, which you'll have to figure out yourself. The proverbial "innermost loop" in your case is the if (i >= M), and this part runs $2^M$ times (once for each subset). If the complexity of the innermost loop is $C$, then the overall complexity of the code would be $O(2^M C)$, since the complexity of all other parts pales in comparison.

Yuval Filmus
  • 280,205
  • 27
  • 317
  • 514