递归的注意事项
1:递归的问题求解的思路:
我们遇到的问题直接并不好解决,但是发现将原问题拆分成其子问题之后,子问题与原问题有相同的解法,等子问题解决之
后,原问题就迎刃而解了。
2:递归问题一般别展开。
3:
执行语句结束之后再回来执行剩下的语句
还有就是 递的次数 == 归的次数
4:
栈帧的角度思考递归
练习一:汉诺塔问题
//汉诺塔问题
public static void main3(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
Test2 test2 = new Test2();
test2.hannuo(n , 'A' ,'B' ,'C');
}
/**
* @param n : 移动的个数
* @param a :起始位置
* @param b :中转位置
* @param c :目标位置
* */
public void hannuo(int n ,char a ,char b, char c){
if(n == 1){
System.out.print(a +"-->"+c + " ");
}else{
hannuo(n-1 ,a ,c , b);
System.out.print(a +"-->"+ c + " ");
hannuo(n-1 ,b , a , c);
}
}
练习二:按顺序打印一个数字的每一位(例如 1234 打印出 1 2 3 4) (递归)
//按顺序打印一个数字的每一位(例如 1234 打印出 1 2 3 4) (递归)
public static void main1(String[] args) {
int n = 1234;
Test2 test2 = new Test2();
test2.func(n);
//System.out.println(test2.func(n));
}
public void func(int n){
if(n / 10 == 0){
System.out.print(n % 10+ " ");//执行语句结束之后再回来执行剩下的语句
//return n % 10;
}else{
func(n / 10);
System.out.print(n % 10+ " ");
//return n % 10 +func(n / 10);
}
}
执行语句结束之后再回来执行剩下的语句
Java 是不能获取栈上变量的地址的 ,只能获取堆上的地址
public static void main(String[] args) {
int a = 10;
int b = 20;
//a b 都是局部变量 ,存储在栈上 ,Java 是不能获取栈上变量的地址的 ,只能获取堆上的地址。
//局部变量存储在栈上 , 成员变量存储在堆上。
System.out.println(sum(a , b));
}
public static int sum(int a,int b){
return a+b;
}
打印X型图案
//打印X型图案
public static void main6(String[] args) {
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext()){//多组输入 , scanner.hasNext()返回值是Boolean类型
int num = scanner.nextInt();
int i = 0;
int j = 0;
for (i = 0; i < num; i++) {
for (j = 0; j < num; j++) {
if(i == j || i + j == num-1){
System.out.print("*");
}else{
System.out.print(" ");
}
}
//一行弄完了再弄下一行
System.out.println();
}
}
}
answer:
8
* *
* *
* *
**
**
* *
* *
* *
10
* *
* *
* *
* *
**
**
* *
* *
* *
* *
多组输入注意:
hasNextInt : 判断是否有下一个整数 , 有的话继续执行。
. nextInt : 读入一个整数