Recursive & DP

Tail Recursion

 

 

 

 

Why space complexity is less in case of loop ?

Before explaining this I am assuming that you are familiar with the knowledge that’s how the data stored in main memory during execution of a program.In brief,when the program executes,the main memory divided into three parts.One part for code section,second one is heap memory and another one is stack memory.Remember that the program can directly access only the stack memory , it can’t directly access the heap memory so we need the help of pointer to access the heap memory.

Let’s now understand why space complexity is less in case of loop ?

In case of loop when function “(void fun(int y))” executes there only one activation record created in stack memory(activation record created for only ‘y’ variable) so it takes only ‘one’ unit of memory inside stack so it’s space complexity is O(1) but in case of recursive function every time it calls itself for each call a separate activation record created in stack.So if there’s ‘n’ no of call then it takes ‘n’ unit of memory inside stack so it’s space complexity is O(n).

so loop takes less space than the recusive.And recursive call does not remeber the old value, so sometimes it is better to use the DP.

 

posted @ 2020-11-12 08:04  John_K  阅读(119)  评论(0)    收藏  举报