返回文章列表

【PHP】匿名函数递归

2024年8月16日
PHP

普通递归

普通函数的递归,大家应该都清楚,并且也都用过,比如说斐波那契数列,快速排序等等。

#递归实现斐波那契额数列
function fibonacci(int $in) : int
{
  if ($n <= 0) {
    return $n;
  } elseif ($n === 1) {
    return 1;
  } else {
    return fibonacci($n - 2) + fibonacci($n - 1);
  }
}
#快速排序
function QuickSort(array $arr) : array
{
  $length = count($arr);
  if ($length <= 1) {
    return $arr;
  }
  $mid = $arr[0];
  $littleArr = [];
  $bigArr = [];
  for ($i = 1; $i < $length; $i++) {
    if ($arr[$i] <= $mid) {
      $littleArr[] = $arr[$i];
    }
    if ($arr[$i] > $mid) {
      $bigArr[] = $arr[$i];
    }
  }
  $littleArr = QuickSort($littleArr);
  $littleArr[] = $mid;
  $bigArr = QuickSort($bigArr);
  return array_merge($littleArr, $bigArr);
}

匿名函数递归

最近在用php刷一些算法方面的题,就看到一个实现BFS算法的方式, 题目详见LeetCode

class TreeNode
{
  public $val;
  public $left;
  public $right;

  public function __construct($val)
  {
    $this->val = $val;
  }
}

$twenty = new TreeNode(20);
$twenty->left = new TreeNode(15);
$twenty->right = new TreeNode(7);
$one = new TreeNode(3);
$one->left = new TreeNode(9);
$one->right = $twenty;

function levelOrderBottom(TreeNode $root, int $level)
{
  $arr = [];
  $dfs = function ($root, $level) use (&$arr, &$dfs){
    if (is_null($root)) {
      return;
    }
    $dfs($root->left, $level + 1);
    $dfs($root->right, $level + 1);
    $arr[$level][] = $root->val;
  };
  $dfs($root, 0);
  return $arr;
}
var_dump(levelOrderBottom($one, 0));

在匿名函数使用use关键字可以使用函数外部的变量,同样我们也可以使用这个匿名函数。整个过程就是这样了。