一、函數的遞歸
①漢諾塔問題
將n個盤子從A座移到C座可以分解爲以下三個步驟:
(1)將A上n-1個盤藉助C座先移到B座上。
(2)把A座上剩下的一個盤移到C座上。
(3)將n-1個盤從B座藉助於A座移到C座上。
#include<stdio.h>
int cnt;
int main()
{
void hanoi(int n,char one,char two,char three);
int n;
printf("input the number of diskes:");
scanf("%d",&n);
printf("The step to moveing %d diskes:\n",n);
hanoi(n,'A','B','C');
}
void hanoi(int n,char one,char two,char three)
{
void move(char x,char y);
if(n==1)
{
move(one,three);
}
else
{
hanoi(n-1,one,three,two);
move(one,three);
hanoi(n-1,two,one,three);
}
}
void move(char x,char y)
{
cnt++;
printf("step %d: %c--->%c\n",cnt,x,y);
}
關於遞歸:要完成最後一步,那麼最後一步的前一步要做什麼。
在求f(n, other variables)的時候,你就默認f(n -1,other variables)已經被求出來了——至於怎麼求的,這個是計算機通過回溯求出來的。( 你把n-1當成一個整體就好了)