recursiontime-complexitysubsetbacktrackingrecurrence

finding time complexity of backtracking solution for generate all subset problem


Given the problem of distinct integers, generate all subsets. https://www.interviewbit.com/problems/subset/

I have found two solutions.

first solution::

 void helper_subsets(vector<vector<int>> &res , vector<int> &A , 
    vector<int> &subset ,int current)
{
    if(current == A.size())
        res.push_back(subset) ;
    else
    {
        helper_subsets(res,A,subset,current+1) ;
        subset.push_back(A[current]) ;
        helper_subsets(res,A,subset,current+1) ;
        subset.pop_back() ;
    }
}

vector<vector<int> >subsets(vector<int> &A) {
    vector<vector<int>> res ;

    sort(A.begin(),A.end()) ;

    vector<int> subset ;

    helper_subsets(res , A , subset , 0 ) ;

    sort(res.begin(),res.end()) ;
    return res ;
}

Second solution ::

void helper_subsets(vector<vector<int>> &res , vector<int> &A , 
    vector<int> &subset ,int current)
{
    res.push_back(subset) ;
    for(int i = current ; i < A.size() ; i++)
    {
        subset.push_back(A[i]) ;
        helper_subsets(res,A,subset,i+1) ;
        subset.pop_back() ;
    }
}

vector<vector<int> > subsets(vector<int> &A) {
    vector<vector<int>> res ;

    sort(A.begin(),A.end()) ;

    vector<int> subset ;

    helper_subsets(res , A , subset , 0 ) ;

    sort(res.begin(),res.end()) ;
    return res ;
}

The problem is that I am able to calculate the time complexity of the first solution mathematically as well using recursion tree. t(n) = 2t(n-1) + c (i.e 2 recursive calls with size n-1 and some constant time for each n) t(n) = O(2^n) by solving the above recurrence relation.

But with the second solution, I am not able to define recurrence relation to finally use back substitution to get the time complexity and could not get it by recurrence tree method.Please help me find time complexity of second solution.


Solution

  • The analogous recurrence relation for problem 2 is:

           n - 1
    T(n) =   Σ  T(n - i) + c
           i = 1
    

    – which follows from the for-loop from current to A.size(). To solve this, expand the first term:

    T(n) = T(n - 1) + T(n - 2) + T(n - 3) + ... + T(1) + c
           --------
               |
         =     |      T(n - 2) + T(n - 3) + ... + T(1) + c +
                --->  T(n - 2) + T(n - 3) + ... + T(1) + c
    
         = 2 * [T(n - 2) + T(n - 3) + ... + T(1) + c]
         = 2 * T(n - 1)
    

    i.e., a very similar recurrence relation differing only by a constant. It still evaluates to O(2^n), taking the base case to be T(1) = O(1).