The difference between recursion and loop python_What is the most essential difference between recursion and loop

Functionally, all recursive implementations can be implemented with loops, but sometimes recursive implementations are more convenient. In terms of efficiency, loops are generally greater than recursion.

As the landlord said, each recursion creates a new scope, and the level is actually in a different scope, each level is the level+1 of the previous scope, and each level is different , so instead of 0+1, these levels are different variables, although they are just different variables with the same name.

Write a loop version for you, without optimization, the level can not be an array, it is written to let you know that the level of each recursion is not the same level

public function noLimitCategory($categories,$top_id=0,$level=0){

static $arr=array(); // This static can not be, because it is not recursive

$top_id = array();

$level = array();

$top_id[0] = 0;

$level[0] = 0;

$i = 0;

do{

foreach($categories as $category){

$category['level']=$level[$i];

if($category['parent_id']==$top_id[$i]){

$arr[]=$category;

$top_id[] = category['id'];

$level[] = $level[$i] + 1;

}

}

$i++;

}while($i

//echo '

';

//var_dump($categories);exit;

return $arr;

}

It can be seen that if it is written as a loop, you need to save or distinguish top_id and level by yourself, while recursion is in a different scope, so it implies different top_id and level.

我们所说的递归效率低是说,每次函数调用,我们不仅仅需要多创建一个top_id和level(上面的循环就是只是多创建了几个top_id和level),而且要有其他地方保存每一次函数调用的返回地址和复制一次categories 的引用。另外我说过了,在循环中level是可以不作为数组的,所以其实只是需要多分配保存top_id的空间。因此,循环效率高于递归。

递归本质上是使用编译器提供的栈来实现这个算法,所以如果写成循环的形式需要自己维护这个栈的结构,并且在此基础上把不需要的东西都优化掉(一定可以优化掉的是函数的返回地址),就会得到一个等价的循环版。另外,不是所有的程序使用栈效率最高,而该写成循环就可以使用其他的数据结构达到优化的目的。问题就是循环需要自己维护一个栈(在某些情况下可以优化掉这个栈),所以代码就复杂了。

对于一般人来说,一旦学会了递归,遇到稍微复杂一点儿的贪心算法,动态规划或是遍历等问题,那么最容易想到的就是递归。从这个角度来说递归程序更简单(简单就是大家都能想到的意思)。

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325664402&siteId=291194637