【问题标题】:How to get all possible decision trees with php如何使用 php 获取所有可能的决策树
【发布时间】:2013-12-01 09:34:33
【问题描述】:

我正在寻找使用 php 构建所有可能的决策树。我正在寻找的内容与this answer 完全相同,但是,我需要在 php 中使用它,而且我在解释 LINQ 时遇到了困难;而stringbuilder 可能需要是一个数组。

【问题讨论】:

    标签: php tree binary-tree


    【解决方案1】:

    这是一个 PHP 版本,它返回由数组组成的树集合。

    function AllBinaryTrees($size = 0)
    {
      // empty tree, size=0
      if ($size === 0) { return array(null); }
    
      // otherwise take 1 from the size for the root of the current subtree and
      // split the rest over the subtrees in every possible way
      $trees = array();
      $size --;
    
      for ($leftsize=0; $leftsize <= $size; $leftsize ++)
      {
         foreach(AllBinaryTrees($leftsize) as $left)
           foreach(AllBinaryTrees($size-$leftsize) as $right)
           {
              // add the new tree to the collection
              $trees[] = array('left' => $left, 'right' => $right);
           }
      }
      return $trees;
    }
    

    请注意,这不是最有效的方法,因为我们一次又一次地生成给定大小的子树,因此缓存它们会更好。 我们可以将此函数包装在一个类中,该类为每个大小的树保存一个缓存。

    【讨论】:

      【解决方案2】:

      这是带有记忆的算法:

      function AllBinaryTrees($size)
      {
          static $cache = [];
      
          if ($size <= 0) {
              return [null];
          }
      
          if (isset($cache[$size])) {
              return $cache[$size];
          }
      
          $trees = [];
      
          foreach (range(0, $size - 1) as $i) {
             foreach (AllBinaryTrees($i) as $left) {
                 foreach(AllBinaryTrees($size - 1 - $i) as $right) {
                     $trees[] = ['left' => $left, 'right' => $right];
                 }
             }
          }
      
          return $cache[$size] = $trees;
      }
      

      【讨论】:

        猜你喜欢
        • 2019-05-10
        • 2016-03-08
        • 2014-04-22
        • 1970-01-01
        • 2014-08-28
        • 1970-01-01
        • 2018-03-03
        • 2012-10-18
        • 2015-11-06
        相关资源
        最近更新 更多