问题:一个楼梯有n个台阶,每次上一个或两个台阶,共有多少种上法, 每种走法的步骤是什么样的?
这个简单问题,我们通常的方法是写一个递归调用,简单明了。但是,这里通过类的叠加来实现,虽然本身没有太大的意义,但是这种设计的用途还是满多的,可以自己考虑考虑.
1 <?php
2
3 //一个楼梯有n个台阶,每次上一个或两个台阶,共有多少种上法, 每种走法的步骤是什么样的.
4
5 define('TOTLE_STEP', 10);
6
7 $p = '';
8
9 $obj = new step($p, 0, 0);
10
11 $obj->go();
12
13 class step{
14
15 var $parent;
16
17 var $count;
18
19 var $step;
20
21 var $son1;
22
23 var $son2;
24
25 function step(&$parent, $step, $count){
26
27 $this->parent = &$parent;
28
29 $this->step = $step;
30
31 $this->count = $count + $step;
32
33 }
34
35 function go(){
36
37 if($this->count==TOTLE_STEP)
38
39 $this->callback();
40
41 if($this->count<=TOTLE_STEP-1){
42
43 $this->son1 = new step($this, 1, $this->count);
44
45 $this->son1->go();
46
47 }
48
49 if($this->count<=TOTLE_STEP-2){
50
51 $this->son2 = new step($this, 2, $this->count);
52
53 $this->son2->go();
54
55 }
56
57 }
58
59 function callback($str=''){
60
61 if($this->parent!=null){
62
63 $str = $this->step.$str;
64
65 $this->parent->callback('--'.$str);
66
67 }else{
68
69 echo $str.'<br>';
70
71 }
72
73 }
74
75 }
76
77 ?>
78
2
3 //一个楼梯有n个台阶,每次上一个或两个台阶,共有多少种上法, 每种走法的步骤是什么样的.
4
5 define('TOTLE_STEP', 10);
6
7 $p = '';
8
9 $obj = new step($p, 0, 0);
10
11 $obj->go();
12
13 class step{
14
15 var $parent;
16
17 var $count;
18
19 var $step;
20
21 var $son1;
22
23 var $son2;
24
25 function step(&$parent, $step, $count){
26
27 $this->parent = &$parent;
28
29 $this->step = $step;
30
31 $this->count = $count + $step;
32
33 }
34
35 function go(){
36
37 if($this->count==TOTLE_STEP)
38
39 $this->callback();
40
41 if($this->count<=TOTLE_STEP-1){
42
43 $this->son1 = new step($this, 1, $this->count);
44
45 $this->son1->go();
46
47 }
48
49 if($this->count<=TOTLE_STEP-2){
50
51 $this->son2 = new step($this, 2, $this->count);
52
53 $this->son2->go();
54
55 }
56
57 }
58
59 function callback($str=''){
60
61 if($this->parent!=null){
62
63 $str = $this->step.$str;
64
65 $this->parent->callback('--'.$str);
66
67 }else{
68
69 echo $str.'<br>';
70
71 }
72
73 }
74
75 }
76
77 ?>
78