45fan.com - 路饭网

搜索: 您的位置主页 > 网络频道 > 阅读资讯:使用“类”代替递归的步骤

使用“类”代替递归的步骤

2016-09-01 18:02:22 来源:www.45fan.com 【

使用“类”代替递归的步骤

/***************************

* author : 大龄青年

* email :
wenadmin@sina.com

* from: http://blog.csdn.net/hahawen

* 转载请保留这部分信息,谢谢

***************************/

问题:一个楼梯有n个台阶,每次上一个或两个台阶,共有多少种上法, 每种走法的步骤是什么样的?

这个简单问题,我们通常的方法是写一个递归调用,简单明了。但是,这里通过类的叠加来实现,虽然本身没有太大的意义,但是这种设计的用途还是满多的,可以自己考虑考虑。

<?php

//一个楼梯有n个台阶,每次上一个或两个台阶,共有多少种上法, 每种走法的步骤是什么样的.

define('TOTLE_STEP', 10);

$p = '';

$obj = new step($p, 0, 0);

$obj->go();

class step{

var $parent;

var $count;

var $step;

var $son1;

var $son2;

function step(&$parent, $step, $count){

$this->parent = &$parent;

$this->step = $step;

$this->count = $count + $step;

}

function go(){

if($this->count==TOTLE_STEP)

$this->callback();

if($this->count<=TOTLE_STEP-1){

$this->son1 = new step($this, 1, $this->count);

$this->son1->go();

}

if($this->count<=TOTLE_STEP-2){

$this->son2 = new step($this, 2, $this->count);

$this->son2->go();

}

}

function callback($str=''){

if($this->parent!=null){

$str = $this->step.$str;

$this->parent->callback('--'.$str);

}else{

echo $str.'<br>';

}

}

}

?>

 

本文地址:http://www.45fan.com/a/question/70912.html
Tags: PHP 代替 递归方法
编辑:路饭网
关于我们 | 联系我们 | 友情链接 | 网站地图 | Sitemap | App | 返回顶部