zoukankan      html  css  js  c++  java
  • io流2

                                                       递归

          昨天描述了io流的一系列操作,今天来讲一讲递归,前面我们写了很多算法,有很多都可以递归实现,递归简化了代码,比如说n的阶乘,是一种很很好用的编程技巧,

    递归典型问题: 梵塔问题(汉诺塔问题)
    已知有三根针分别用A, B, C表示,在A中从上到下依次放n个从小到大的盘子,现要求把所有的盘子
    从A针全部移到B针,移动规则是:可以使用C临时存放盘子,每次只能移动一块盘子,而且每根针上
    不能出现大盘压小盘,找出移动次数最小的方案.
    /*Name:HANOITOWER
    *Description:solvethehanoitowerproblembyrecursion
    */
    #include<stdio.h>
    #include<stdlib.h>
    /*movenplates:from-->to,
    *thebuffercanbeusedifneeded*/
    inthanoi(intn,charfrom,charbuffer,charto)
    {
        if(n==1)
        {
            /*movetheNO.1platedirectly:from-->to*/
            printf("Moveplate#%dfrom%cto%c
    ",n,from,to);
            /*theNO.1plateismovedsoreturn*/
            return0;
        }
        else
        {
            /*nplatestobemoved:from-->to,
            *movethen-1platesabove:from-->buffer,
            *givethistasktothenextrecursion*/
            hanoi(n-1,from,to,buffer);
            /*then-1platesaboveweremovedtobuffer,
            *sotheNO.nplatecanbemoveddirectly*/
            printf("Moveplate#%dfrom%cto%c
    ",n,from,to);
            /*howeverthen-1platesarestillinbuffer,
            *movethemtotheterminalposition,
            *(the"from"positionhasnoplate,&canbeoneso-calledbuffer)*/
            hanoi(n-1,buffer,from,to);
            /*thetaskgivenisdonesoreturn*/
            return0;
        }
    }
    intmain()
    {
    #defineN4
        /*NplatesinA,let'smovethemtoC*/
        hanoi(N,'A','B','C');
        return0;
    }

    递归分为两种,一种是直接递归,一种是间接递归,个人觉着递归并不是所有情况下都可以用,好使就用。

  • 相关阅读:
    Android中使用WebView, WebChromeClient和WebViewClient加载网页
    Android清除本地数据缓存代码案例
    暴雪hash算法
    C++ 指向类的指针
    Qt VS Tools 的Qt Option add 不上qt版本的问题
    Dom4j完整教程详解
    java中charAt()方法的使用
    Linux环境下C++调试的三板斧
    (转载)Markdown进阶(更改字体、颜色、大小,设置文字背景色,调整图片大小设置居中)
    关于回调函数的理解
  • 原文地址:https://www.cnblogs.com/jingyukeng/p/8927675.html
Copyright © 2011-2022 走看看