当前位置:网站首页>Recursion_ Calculate f (n) =f (n-1) +f (n-2)
Recursion_ Calculate f (n) =f (n-1) +f (n-2)
2022-07-22 03:20:00 【haohaounique】
subject :
1 、1、2、3、5、8.... Calculation 103 Value
law :f(n)=f(n-1)+f(n-2)
Basic Edition : Algorithm implementation
public static int getResult(int num){ if (num<=2) return 1; return getResult(num - 1) + getResult(num - 2); }
Recursion of memo mode ( Cache the results of previous calculations to reduce the solution of overlapping subproblems )O(N):
private static final Map<Integer, Long> cache = new HashMap<>(); public static long getResult(int num){ if (num<=2) return 1; return cache.computeIfAbsent(num,k->getResult(num - 1) + getResult(num - 2)) ; }
computeIfAbsent() Method pair hashMap It is specified in key Recalculate the value of , If this doesn't exist key, Add to hashMap in
Dynamic programming method O(N)
public static int getResult2(int n) { if (n == 0) return 0; if (n == 1 || n == 2) return 1; int[] dp = new int[n + 1]; dp[0] = dp[1] = 1; for (int i = 2; i <= n; i++) { dp[i] = dp[i - 1] + dp[i - 2]; } return dp[n]; }
State compression O(1)
public static int getResult3(int n) { if (n == 0) return 0; if (n == 1 || n == 2) { return 1; } int prev = 1; int current = 2; for (int i = 3; i <= n; i++) { int sum = prev + current; prev = current; current = sum; } return current; }
边栏推荐
猜你喜欢
[JS reverse hundred examples] a public resource trading network, reverse analysis of announcement URL parameters
Harbor warehouse construction and simple use
Mathematical angles, radians and trigonometric functions in the game
Deque容器的系列操作( 详解 )
Stream流对List集合筛选重复字段
ECCV 2022 | multi domain long tailed distributed learning to solve the problem of unbalanced domain generalization
Baidu map, Gaode map, Tencent map Trinity map positioning development
Simple shader practice record 5-Screen gradient
游戏中的数学之各种插值
js教程实践(JS基础)
随机推荐
Sign up now | how to reduce the cost of cloud data analysis?
策略模式改写if else 高级使用
centos7安装mysql5.7全过程及各种问题解答
游戏中的数学之角与弧度、三角函数
likeshop单商户SAAS商城系统无限多开
图卷机神经网络-GCNN
怎样才能让需求无法如期顺利上线(三)开发阶段
【 JS Reverse 100 examples】 Reverse Analysis of Announcement URL Parameters in a Public Resource Trading Network
6.0系统中Fragment请求权限所踩过的坑
day 2
Mumu simulator views log output through monitor
Specific use of typescript in cocos
String类常用方法
Instrumentation, three-phase ammeter LCD segment code LCD low-power anti-interference drive ic-vk2c23a/b (dic/cob can be output)
Batch efficient feature decomposition of eccv2022 small and medium-sized matrices
Jenkins安装并配置加速器
Tips for using efficient development tools
[machine learning] hierarchical clustering
剑指 Offer 47. 礼物的最大价值
day 3