当前位置:网站首页>Dynamic programming problem (1)
Dynamic programming problem (1)
2022-07-29 00:21:00 【std i hurt o love】
One 、 Fibonacci sequence
Solution 1 : recursive
class Solution {
public:
int Fibonacci(int n) {
if(n==1||n==2)
return 1;
else
return Fibonacci(n-1)+Fibonacci(n-2);
}
};
Time complexity :O(2^n) Each recursion calls two recursions , So present 2 The exponential growth of
Spatial complexity :O(n), The maximum depth of the recursive stack
Solution 2 : iteration ( recommend )
class Solution {
public:
int Fibonacci(int n) {
// from 0 Start , The first 0 Item is 0, The first is 1
if(n <= 1)
return n;
int res = 0;
int a = 0;
int b = 1;
// because n=2 Shi yewei 1, When initializing a=0,b=1
for (int i = 2; i <= n; i++){
// The third item starts with the sum of the first two items , Then keep the latest two , Update data addition
res = (a + b);
a = b;
b = res;
}
return res;
}
};
Time complexity :O(n), among n Number entered for ,n Sub iteration
Spatial complexity :O(1), Constant level variable , There is no additional auxiliary space
Solution 3 : Dynamic programming
- Create a length of n+1 Array of , Because only n+1n Can have subscript n term , Before we use it to record n Term Fibonacci sequence .
- According to the formula , Initializing page 0 Xiang and di 1 term ( In the title is 1 Xiang and di 2 term , It's essentially the same ).
- Traversal array , According to the formula, a certain term is equal to the sum of the first two terms , Fill up the subsequent elements of the array , You can get fib[n]
class Solution {
public:
int Fibonacci(int n) {
if(n<=1)
return n;
int*fib=new int[n+1];
fib[0]=0,fib[1]=1;
for(int i=2;i<=n;i++)
fib[i]=fib[i-1]+fib[i-2];
return fib[n];
}
};
Time complexity :O(n), One for Loop traversal
Spatial complexity :O(n), Created a size of n+1 Dynamic array of
Two 、 Skip step
Solution 1 : recursive
class Solution {
public:
int jumpFloor(int number) {
// Here I 0 Items for 1, The first 1 Items for 1
if(number <= 1)
return 1;
else
// Recursive subproblem addition
return jumpFloor(number - 1) + jumpFloor(number - 2);
}
};
Time complexity :O(2^n), Each recursion calls two recursions , So present 2 The exponential growth of
Spatial complexity :O(n), The maximum depth of stack space is n
Solution 2 : Recursive optimization
- Use dp Array records the value of the previous sequence .
- Function below 2 Sequence of terms , Go straight back to 1.
- For the present n, If dp If it exists in the array, it can be used directly , Otherwise, recursively call the function to calculate the sum of the two sub problems .
class Solution {
public:
// Set global variables , Because there is no 0, Available 0 Make the initial identification value
int dp[50] = {
0};
int F(int n){
if(n <= 1)
return 1;
// if dp If there is a value in, you don't need to recursively add it again
if(dp[n] != 0)
return dp[n];
// if dp If there is no value in, you need to recursively add it again
return dp[n] = F(n - 1) + F(n - 2);
}
int jumpFloor(int number) {
return F(number);
}
};
Time complexity : Each number is calculated only once , So it's O(n)
Spatial complexity :O(n), Maximum depth of stack space
Solution 3 : Iterative addition ( recommend )
- lower than 2 Sequence of terms , Go straight back to n.
- Initializing page 0 term , With the first 1 Items are 0,1.
- From 2 A start , Gradually accumulate according to the formula , And update the addition number to always be the first two items of the next item .
class Solution {
public:
int jumpFloor(int number) {
// from 0 Start , The first 0 Item is 0, The first is 1
if(number <= 1)
return 1;
int res = 0;
int a =1;
int b = 1;
// because n=2 Shi yewei 1, When initializing a=0,b=1
for(int i = 2; i <= number; i++){
// The third item starts with the sum of the first two items , Then keep the latest two , Update data addition
res = a + b;
a = b;
b = res;
}
return res;
}
};
Time complexity :O(n), among nnn Number entered for
Spatial complexity :O(1), Constant level variable , There is no additional auxiliary space
Method four : Dynamic programming
class Solution {
public:
int jumpFloor(int number) {
if(number<=1)
return 1;
int*res=new int[number+1];
res[0]=1,res[1]=1;
for(int i=2;i<=number;i++)
res[i]=res[i-1]+res[i-2];
return res[number];
}
};
Time complexity :O(n), Traversed once with a length of n Array of
Spatial complexity :O(n), Set up an array auxiliary
3、 ... and 、 Minimum cost of climbing stairs
solution : Dynamic programming
- You can use an array to record every time you climb to the i Minimum cost of stairs , Then the state will be transferred once every step is added , The final result .
- The initial state ) Because it can be directly from the 0 Grade or grade 1 The steps begin , Therefore, the cost of these two levels is directly 0.
- State shift ) One step at a time , There are only two cases , Or it takes a step up the front step , Or two steps up the first two steps , Because of the cost on the front steps, we all got , Therefore, the minimum value can be updated every time , The transfer equation is dp[i]=min(dp[i−1]+cost[i−1],dp[i−2]+cost[i−2])
class Solution {
public:
int minCostClimbingStairs(vector<int>& cost) {
//dp[i] It means to climb to the first i The minimum cost of stairs
vector<int> dp(cost.size() + 1, 0);
for(int i = 2; i <= cost.size(); i++)
// Choose the smallest plan each time
dp[i] = min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]);
return dp[cost.size()];
}
};
Time complexity :O(n), among n For the given array length , Traversing the array once
Spatial complexity :O(n), Auxiliary array dp Space
边栏推荐
- 【C】 Replace spaces and realize binary parity bit exchange of integers by macros
- Event extraction and documentation (2018)
- Use hutool tool class to operate excel with more empty Sheet1
- Three years after graduation, write to you and me who may be confused [turn]
- html+css+php+mysql实现注册+登录+修改密码(附完整代码)
- 聊聊异步编程的 7 种实现方式
- MQ 消息丢失、重复、积压问题,如何解决?
- Principle of meter skipping
- Solution: direct local.Aar file dependencies are not supported when building an aar
- Feign call fails. JSON parse error illegal character ((ctrl-char, code 31)) only regular white space (R
猜你喜欢

Visual full link log tracking

动态规划问题(五)

Attack and defense world web master advanced area web_ php_ unserialize

Android studio连接MySQL并完成简单的登录注册功能

feign调用不通问题,JSON parse error Illegal character ((CTRL-CHAR, code 31)) only regular white space (r

【C】 Introduction and Simulation Implementation of ATOI and offsetof

SQL implementation merges multiple rows of records into one row

Using recursion and chain header interpolation to realize the group turnover of linked lists -- leetcode25 K group turnover linked lists

【C】 Replace spaces and realize binary parity bit exchange of integers by macros

Idea2021.2 installation and configuration (continuous update)
随机推荐
Applet waterfall flow, upload pictures, simple use of maps
Install MySQL using Yum for Linux
Locally connect to redis on Windows Server
IDEA报错Error running ‘Application‘ Command line is too long解决方案
vscode下链接远程服务器安装插件失败、速度慢等解决方法
Google browser, no installation required
Attack and defense world web master advanced area PHP_ rce
Leetcode64. Minimum path sum
【微服务】Nacos集群搭建以及加载文件配置
Field injection is not recommended solution
Servlet运行原理_API详解_请求响应构造进阶之路(Servlet_2)
时间序列统计分析
Attack and defense world web master advanced area web_ php_ include
@PostConstruct注解详解
mysql索引失效的常见9种原因详解
Build SSM project with JSP as view parser
Feign call fails. JSON parse error illegal character ((ctrl-char, code 31)) only regular white space (R
centos7安装mysql8
html+css+php+mysql实现注册+登录+修改密码(附完整代码)
Advanced area of attack and defense world web masters -baby Web