1. 程式人生 > >遞迴的幾個例子

遞迴的幾個例子

一,遞迴階乘

n! =n * (n - 1)....*1

#include<iostream>
using namespace std;
long a(int n)
{
	if(n == 0)
		return 1;
	else
		return n * a(n-1);
}
int main()
{
	cout << a(5) << endl;
	return 0;
}

二,遞迴求和

#include<iostream>
using namespace std;
long a(int n)
{
	if(n == 0)
		return 0;
	else
		return n + a(n-1);
}
int main()
{
	cout << a(5) << endl;
	return 0;
}


三,漢諾塔問題


#include<iostream>
using namespace std;
int i;
void move(int n,char from,char to)
{
	cout << "第" << i++ << "步:將" << n << "號盤子" << from << "---->" << to << endl;
}
//漢諾塔遞迴函式  
//n表示要將多少個"圓盤"從起始柱子移動至目標柱子  
//start_pos表示起始柱子,tran_pos表示過渡柱子,end_pos表示目標柱子  
void Hanio(int n,char start_pos,char tran_pos,char end_pos){  
    if(n==1){    //很明顯,當n==1的時候,我們只需要直接將圓盤從起始柱子移至目標柱子即可.  
        move(n,start_pos,end_pos);  
    }  
    else{  
        Hanio(n-1,start_pos,end_pos,tran_pos);   //遞迴處理,一開始的時候,先將n-1個盤子移至過渡柱上  
        move(n,start_pos,end_pos);                //然後再將底下的大盤子直接移至目標柱子即可  
        Hanio(n-1,tran_pos,start_pos,end_pos);    //然後重複以上步驟,遞迴處理放在過渡柱上的n-1個盤子  
                                                  //此時藉助原來的起始柱作為過渡柱(因為起始柱已經空了)  
    }  
}  
int main(){  
    int n;  
    cout << "輸入需要移動盤子的個數:" << endl;
    cin >> n;
    i = 1;   //全域性變數賦初始值  
    Hanio(n,'A','B','C');  
    cout << "最後總的步數為" << (i-1) << endl;;  
    return 0;  
}