1.题目描述:求n的阶乘(递归方法)
//1.递归求n的阶乘
public static int factor(int n){
if(n == 1){
return 1;
}
return n * factor(n - 1);
}
public static void main1(String[] args) {
int n = 5;
int ret = factor(n);
System.out.println("ret = " + ret);
}
}
2.题目描述:按顺序打印一个数字的每一位——如1334 ——打印 1 2 3 4
//2.按顺序打印一个数字的每一位——如1334 ——打印 1 2 3 4
public static void print(int num){
if(num > 9){
print(num / 10);
}
System.out.print(num % 10 + " ");
}
public static void main(String[] args) {
int n = 123;
print(n);
}
3.题目描述:递归求1 + 2 + 3 + ... + 10的和
//3.递归求1 + 2 + 3 + ... + 10的和
public static int sum(int num){
if(num == 1){
return 1;
}
return num + sum(num - 1);
}
public static void main(String[] args) {
int ret = sum(10);
System.out.println(ret);
}
4.题目描述:输入一个非负整数,返回租车行它的数字之和——如1729 ——返回1 + 7 + 2 + 9 = 19
//4.递归方法:输入一个非负整数,返回组成它的数字之和
public static int sum1(int num){
if(num < 10){
return num;
}
return num % 10 + sum1(num / 10);
}
public static void main(String[] args) {
int ret = sum1(1729);
System.out.println(ret);
}
5.题目描述:求斐波那契数列
(1)递归实现
//5.求斐波那契数列
//(1)递归实现
public static int fib(int n){
if(n == 1 || n== 2){
return 1;
}
return fib(n - 1) + fib(n - 2);
}
public static void main(String[] args) {
int ret = fib(40);
System.out.println(ret);
}
(2)循环(迭代)实现
//(2)循环(迭代)实现
public static int fib1(int n){
int f1 = 1;
int f2 = 1;
int cur = 1;
for (int i = 0; i <= n; i++) {
cur = f1 + f2;
f1 = f2;
f2 = cur;
}
return cur;
}
public static void main(String[] args) {
int ret = fib(40);
System.out.println(ret);
}
6.题目描述:汉诺塔问题
//6.汉若塔问题
public static void move(int n,char pos1,char pos2){
if(n == 1){
System.out.println(pos1 + "->" + pos2);
}
}
public static void hanuota(int n,char pos1,char pos2 ,char pos3){
if(n == 1){
move(n,pos1,pos3);
}
else{
hanuota(n - 1,pos1,pos3,pos2);//将 n - 1 个盘子看成整体,借助 C 从 A 移到 B
move(n,pos1,pos3);//将第 n 个盘子从 A 移到 C
hanuota(n - 1,pos2,pos1,pos3);//将 n - 1 个盘子借助 A 从 B 移到 C
}
}
public static void main(String[] args) {
int n = 4;
char pos1 = 'A';
char pos2 = 'B';
char pos3 = 'C';
hanuota(n,pos1,pos2 ,pos3);
}
7.题目描述:青蛙跳台阶问题——递归实现
一只青蛙一次可以跳上1 级台阶,也可以跳上2级台阶。求该青蛙跳上n级的台阶总共需要多少种跳法;
分析:1 个台阶 —— 1 种 方法
2 个台阶 —— 2 种方法
3 个台阶 —— 3 种方法
4 个台阶 —— 5 种方法
...
n 个台阶 —— (n - 1) + (n - 2) 种方法
//7.青蛙跳台阶问题——递归实现
public static int tol(int n){
if(n == 1){
return 1;
}
else if(n == 2){
return 2;
}else{
return tol(n - 1) + (n - 2);
}
}
public static void main(String[] args) {
System.out.println("请输入台阶数:");
Scanner sc = new Scanner(System.in);
int ret = sc.nextInt();
System.out.println(tol(ret));
}