搜尋:recursion
遞迴函式在定義中使用函數自己
用遞回來定義
一般定義
int fac(int n) {
if (n == 0) return 1;
return n * fac(n-1);
}int f(int n) {
if(n <= 2)
return 1
return f(n - 1) + f(n - 2)
}練習:c002. 10696 - f91
遞迴終止條件: 遞迴到某一程度要停止遞迴,否則會出現TLE 或是 segementation fault
遞迴公式:遞迴就是自己定義自己,在寫遞迴之前要先清楚知道遞迴公式的長相
練習: f640. 函數運算式求值
#include <bits/stdc++.h>
using namespace std;
int main()
{
int x, y;
cin >> x >> y;
while(x % y && y != 0)
{
int tmp = x % y;
x = y;
y = tmp;
}
cout << y << endl;
return 0;
}
int gcd(int a, int b)
{
if (b == 0) return a;
return gcd(b, a % b);
}a024. 最大公因數(GCD)
搬N個盤子A->C,等於
1. 搬(N-1)個盤子A->B
2. 搬1個盤子A->C
3. 搬(N-1)個盤子B->C
gContent
def hanoi(n,a,b,c): #n個,從1搬到3(從a到c)
if n==1:
print(f"Move ring from {a} to {c}")
else:
hanoi(n-1, a,c,b) #(n-1)個,從1搬到3(從a到b)
hanoi( 1, a,b,c) #(1)個,從1搬到3(從a到c)
hanoi(n-1, b,a,c) #(n-1)個,從1搬到3(從b到c)
hanoi(3,"A","B","C")練習: a227. 三龍杯 -> 河內之塔
#include <bits/stdc++.h>
using namespace std;
void hanoi(int n, char src, char dest, char tmp)
{
if (n == 1) {
cout << "Move 1 disk from " << src << " to " << dest << endl;
} else {
hanoi(n - 1, src, tmp, dest);//
hanoi(1, src, dest, tmp);
hanoi(n - 1, tmp, dest, src);
}
}
int main() {
hanoi(2, 'A', 'C', 'B');
return 0;
}