递归算法的数据结构和算法 C++和PHP达到

递归算法:它是一种间接的方法调用本身,直接或。

实施过程:按功能或子程序完成。在函数编写代码或子程序直接或间接拥有被称为。你可以完成递归。

(相同类型的问题,子问题到最小问题有已知条件,然后来求解,然后得到结果逐级返回

事实上也是一种循环。

最主要体现:小的代码量攻克了很复杂的问题
特点:
1、递归就是方法里调用自身
2、必须有一个明白的递归结束条件。称为递归出口。
3、简洁可是执行效率较低,一般不提倡使用
4、每一层的返回点、局部变量等开辟了栈来存储,递归次数过多easy造成栈溢出。

实例1:求阶乘
C++代码:
#include<iostream>
int factorial(int n);
int main()
{
    using namespace std;
    int n;
    cout << "请输入一个数字:";
    cin >> n;
    cout << n << "的阶乘为: " << factorial(n) <<endl;
    return 0;
}
int factorial(int n)
{
    if (n == 1)
        return 1;
    return n*factorial(n-1);
}
执行结果:

实例2:数制转换

代码:
#include<iostream>
#include<cstring>
void feelTheBase(char *s, int n, int sys);
int main()
{
    using namespace std;
    char s[60];
    int n,sys;
    cout << "请输入一个整数:";
    cin >> n;
    cout << "请输入要转换的进制类型(2,8,16):";
    cin >> sys;
    feelTheBase(s, n, sys);
    cout << n << "转换成" << sys << "进制结果为: " << s <<endl;
    return 0;
}
void feelTheBase(char *s, int n, int sys)
{
    char bit[] = {"0123456789ABCDEF"};
    int len;
    if (n == 0)
    {
        strcpy(s, "");
        return;
    }
    feelTheBase(s, n/sys, sys);
    len = strlen(s);
    s[len] = bit[n%sys];
    s[len+1] = '';
}
执行结果:


实例3:列出某个文件夹下全部的子文件夹和文件(还能够用scandir函数更方便
PHP实现代码:
<?php
function rec($dir, $lev=0){
    $dh = opendir($dir);
 while (($file = readdir($dh)) != false) {
  if ($file == '.' || $file == '..') {
   continue;
  }
  if (is_dir($dir.'/'.$file)){
      $arr = explode("/",$dir.'/'.$file);
   $lev = count($arr)-3;
      echo str_pad('',$lev, "--")."文件夹".$file."<br/>";
   rec($dir.'/'.$file, $lev+1);
  }else {
   echo str_pad('',$lev, "--").$file."<br/>";
     }
 }
 
 closedir($dh);
}
$dir = "./";
rec($dir);
?>
执行结果:


版权声明:本文博主原创文章,博客,未经同意不得转载。

原文地址:https://www.cnblogs.com/blfshiye/p/4854808.html