递归
昨天描述了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",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",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; }
递归分为两种,一种是直接递归,一种是间接递归,个人觉着递归并不是所有情况下都可以用,好使就用。