1.汉诺塔:请输入盘子数,输出盘子移动的操作步骤。#include <stdio.h>
void move(char from, char to) {
printf("%c to %c\n", from, to);
}
void hanoi(int n, char a, char b, char c) {
if (n == 1)
move(a, c);
else {
hanoi(n - 1, a, c, b);
move(a, c);
hanoi(n - 1, b, a, c);
}
}
void main() {
int n;
scanf("%d", &n);
hanoi(n, 'A', 'B', 'C');
}2.爬楼梯:树老师爬楼梯,他可以每次走1级或者2级,输入楼梯的级数,求不同的走法数。#include <stdio.h>
int stair(int n) {
if (n == 1) return 1;
if (n == 2) return 2;
return stair(n - 1) + stair(n - 2);
}
void main() {
int n;
scanf("%d", &n);
printf("%d", stair(n));
}3.爬楼梯:树老师爬楼梯,他可以每次走1级、2级或者3级,输入楼梯的级数,求不同的走法数。#include <stdio.h>
int stair(int n) {
if (n == 1) return 1;
if (n == 2) return 2;
if (n == 3) return 4;
return stair(n - 1) + stair(n - 2) + stair(n - 3);
}
void main() {
int n;
scanf("%d", &n);
printf("%d", stair(n));
}4.斐波那契数列:请输入项数,输出具体数列。#include <stdio.h>
int fibonacci(int n) {
if (n == 1 || n == 2)
return 1;
return fibonacci(n - 1) + fibonacci(n - 2);
}
void main() {
int n, i;
scanf("%d", &n);
for (i = 1; i <= n; i++)
printf("%d,", fibonacci(i));
} |