目录
递归的概念总结:
1.递归的基础概念
我之前的博客总结
https://blog.csdn.net/yezonghui/article/details/106437881进行过递归的总结。
2.递归的Java代码模板
(模板一定要牢记,灵活使用)
public void recur(int level , int param){
// terminator
if(level > MAX_LEVEL){
return;
}
// process current logic
process(level, param);
// drill down
recur(level:level+1 , newParam);
// restore current status
}
3.递归思维要点:
1)不要人肉进行递归(又费时间又费脑子,还不好写程序,不如直接进行递归代码)
2)找到最近最简方法,将其拆解成可重复的问题(重复子问题)
3)数学归纳法思维
题目一:斐波那契数列
(题目链接:https://leetcode-cn.com/problems/fei-bo-na-qi-shu-lie-lcof/)
写一个函数,输入 n ,求斐波那契(Fibonacci)数列的第 n 项。斐波那契数列的定义如下:
F(0) = 0, F(1) = 1
F(N) = F(N - 1) + F(N - 2), 其中 N > 1.
斐波那契数列由 0 和 1 开始,之后的斐波那契数就是由之前的两数相加而得出。
答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请返回 1。
示例 1:
输入:n = 2
输出:1
示例 2:
输入:n = 5
输出:5
方法一:自己的方法:采用递归
Java源代码:
class Solution {
public int fib(int n) {
return (f(n));
}
public static int f(int a){
if(a ==1){
return 1;
}else if(a ==0){
return 0;
}
else{
return (f(a-1)+f(a-2))%1000000007;
}
}
}
【注意:】上述方法超时,需要进行改进或者另寻它法
方法二:改进的递归方法:由于上面的递归中会重复计算,因此我们可以把一些一些计算过的值存起来。
我们看到上面相同颜色的都是重复计算,当n越大,重复的越多,所以我们可以使用一个map把计算过的值存起来,
每次计算的时候先看map中有没有,如果有就表示计算过,直接从map中取,如果没有就先计算,计算完之后再把结果存到map中。
即:采用hashmap结构把已经计算过的值用hashmap存储下来
Java源代码:
import java.util.HashMap;
import java.util.Map;
public class fblx {
public static void main(String[] args) {
System.out.println(f(5,new HashMap<>()));
}
public static int f(int n, Map<Integer,Integer> map){
if(n<2){
return n;
}
if(map.containsKey(n)){
return map.get(n);
}
int first = f(n-1,map);
map.put(n-1,first);
int second = f(n-2,map);
map.put(n-2,second);
int result = (first+second)%1000000007;
map.put(n,result);
return result;
}
}
【注意】:return 的各处返回,到底如何返回