简体   繁体   中英

How to calculate the space complexity for backtracking?

Question Description

What is a good way to calculate the and the time complexity for backtracking algorithms? 和时间复杂度的好方法是什么?

Example

We want the output combo to have exactly a length of K, and the sol set must be unique

Input: arr: [1,2,3,4,5] K: 4

Output:

[1,2,3,4] //[2,1,3,4] is invalid because it's == [1,2,3,4]

[1,2,3,5]

[1,3,4,5]

[2,3,4,5]

// arr == [1,2,3,4,5]
// K   == 4
// backtrack(arr,4,0,{},...other params we don't care)

void backtrack(vector<int> &arr, int K, int start, vector<int> &sol, ...)
{
     if(sol.size() == K)
     {
         //...
     }
     else
     {
           for(int i = start; i < arr.size(); i++)
           {
              sol.push_back(arr[i]);
              backtrack(arr, K, i+1,sol,...);
              sol.pop_back();
           }
     }
}

I think

The worst space complexity is O(k), because I think when I recur f1(), f2() to f5() won't be called after the whole subtree of f1() is finished.

                   []
      f1()    f2() f3() f4() f()5  
f1.1() f()1.2 ... 

The worst time complexity is O(n^k), where n is the length of the array.

Technically time complexity isn't O(n^k) but something like O(sum from i = 1 to k bin(n,i)) because you don't start searching from the beginning of arr but from the element after the last one on the solution and also don't cut states from which you can't finish like [3] . Usually time complexity in such cases is number of states times average time that you need to get from one state to another.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM