【发布时间】:2013-12-01 09:34:33
【问题描述】:
我正在寻找使用 php 构建所有可能的决策树。我正在寻找的内容与this answer 完全相同,但是,我需要在 php 中使用它,而且我在解释 LINQ 时遇到了困难;而stringbuilder 可能需要是一个数组。
【问题讨论】:
标签: php tree binary-tree
我正在寻找使用 php 构建所有可能的决策树。我正在寻找的内容与this answer 完全相同,但是,我需要在 php 中使用它,而且我在解释 LINQ 时遇到了困难;而stringbuilder 可能需要是一个数组。
【问题讨论】:
标签: php tree binary-tree
这是一个 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;
}
请注意,这不是最有效的方法,因为我们一次又一次地生成给定大小的子树,因此缓存它们会更好。 我们可以将此函数包装在一个类中,该类为每个大小的树保存一个缓存。
【讨论】:
这是带有记忆的算法:
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;
}
【讨论】: