系列文章目录
递归
1、一个问题的解可以分解成几个子问题的解。
2、这个问题与分解之后的子问题,除了数据规模不同,求解思路完全一样
3、存在基线/终止条件
(LeetCode-70)爬楼梯
解题过程:最先想到的是用递归方式
class Solution {
public int climbStairs(int n) {
if(n==1)return 1;
if(n==2)return 2;
return climbStairs(n-1)+climbStairs(n-2);
}
}
但是提交以后会发现超出时间限制,因为里面有着大量的重复计算
解决方法:可以用HashMap保存计算过的数据,如果下次需要求解,可以直接从HashMap里面拿值。
class Solution {
private Map<Integer,Integer> storeMap = new HashMap<>();
public int climbStairs(int n) {
if(n==1)return 1;
if(n==2)return 2;
if(storeMap.get(n)!=null){
return storeMap.get(n);
}else{
int result = climbStairs(n-1)+climbStairs(n-2);
storeMap.put(n,result);
return result;
}
}
}
同时所有递归方法都可以用循环实现,通过 f(n) = f(n-1) + f(n-2) 会发现,只要保存前两次的结果,自底向上累加就可以得到最后的答案
循环实现如下:
class Solution {
public int climbStairs(int n) {
if(n==1)return 1;
if(n==2)return 2;
int result = 0;
int pre = 2;
int prePre = 1;
for(int i = 3; i <= n; i++){
result = pre + prePre;
prePre = pre;
pre = result;
}
return result;
}
}
剑指 Offer 10- I. 斐波那契数列
解题思路:题目和爬楼梯类似,最先想到用爬楼梯的解题方法解题
class Solution {
// public int fib(int n) {
// if(n==0)return 0;
// if(n==1)return 1;
// int result = 0;
// int pre = 1;
// int prePre = 0;
// for(int i = 2;i <= n;i++){
// result = pre+prePre;
// prePre = pre;
// pre = result;
// }
// return result;
// }
private Map<Integer,Integer> storeMap = new HashMap<>();
public int fib(int n) {
if(n==0)return 0;
if(n==1)return 1;
if(storeMap.get(n)!=null){
return storeMap.get(n);
}else{
int result = fib(n-1)+fib(n-2);
storeMap.put(n,result);
return result;
}
}
}
但是提交以后会发现错误,答案没有取模,修改以后:
class Solution {
public int fib(int n) {
if(n==0)return 0;
if(n==1)return 1;
int result = 0;
int pre = 1;
int prePre = 0;
for(int i = 2;i <= n;i++){
result = (pre+prePre)%1000000007;
prePre = pre;
pre = result;
}
return result;
}
// private Map<Integer,Integer> storeMap = new HashMap<>();
// public int fib(int n) {
// if(n==0)return 0;
// if(n==1)return 1;
// if(storeMap.get(n)!=null){
// return storeMap.get(n);
// }else{
// int result = (fib(n-1)+fib(n-2))%1000000007;
// storeMap.put(n,result);
// return result;
// }
// }
}
运行正确