1.认识递归基础知识
什么是方法递归?
递归是一种算法,在程序设计语言中广泛应用。
从形式上说:方法调用自身的形式称为方法递归( recursion)。
递归的形式:
直接递归:方法自己调用自己。
间接递归:方法调用其他方法,其他方法又回调方法自己。
使用方法递归时需要注意的问题:
递归如果没有控制好终止,会出现递归死循环,导致栈内存溢出错误。
2.方法递归三要素
递归的公式: f(n) = f(n-1) * n;
递归的终结点:f(1)
递归的方向必须走向终结点
3.其他应用:文件搜索
阶乘分析:
/**
* 猴子吃桃问题
* 猴子第一天摘下若干桃子,当即吃了一半,觉得好不过瘾,于是又多吃了一个
* 第二天又吃了前天剩余桃子数量的一半,觉得好不过瘾,于是又多吃了一个
* 以后每天都是吃前天剩余桃子数量的一半,觉得好不过瘾,又多吃了一个
* 等到第10天的时候发现桃子只有1个了。
* 需求:请问猴子第一天摘了多少个桃子?
*
①整体来看,每一天都是做同一个事件,典型的规律化问题,考虑递归三要素:
②递归公式: f(n) = (f(n + 1) + 1) * 2
③递归终结点:f(10) = 1
④递归方向:从f(1)到f(10)
*/
public class Test01 {
public static void main(String[] args) {
Integer f = f(1);
System.out.println("第一天摘了:"+f);
}
public static Integer f(Integer n){
if (n==10){
return 1;
}else {
return (f(n + 1) + 1) * 2;
}
}
}
--------------------
public class Test01 {
public static void main(String[] args) {
//2、传入 指定月数 12 获取int数字代表月数
Integer count = getCount(12);
//3、调用getCount方法传递月份,获取结果并输出
System.out.println(count);
}
//1、定义方法getCount,根据月数(int数字month)获取兔子对数
public static Integer getCount(int month){
//1.1、 判断如果month的值是1或者2,直接返回1
if (month==1 || month==2){
return 1;
}else {
//1.2、 否则递归调用getCount方法分别传递month-1和month-2,累加求和并返回
return getCount(month-1)+getCount(month-2);
}
}
}
-------------------
package com.itheima.day09.file;
import java.io.File;
/**
* 在电脑里找QQ的快捷方式
*/
public class QQTest {
public static void main(String[] args) {
File file = new File("E:/");
String name="QQ.exe";
search(file,name);
}
private static void search(File file, String name) {
if (file==null || file.isFile()){
return;
}
File[] files = file.listFiles();
if (files!=null){
for (File fil : files) {
if (fil.isFile()){
if (fil.getName().equals(name)){
System.out.println(fil.getAbsolutePath());
}
}else {
search(fil,name);
}
}
}
}
}