当前位置:网站首页><栈模拟递归>
<栈模拟递归>
2022-07-25 15:23:00 【塔子哥来了】
1.求解斐波那契数列第n项值
#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int maxn = 3e5 +5;
struct Node {
ll x , res , state;
// x 代表输入参数
// res 存储当前答案
// state 代表递归阶段
};
ll f (ll x){
stack<Node> s;
s.push({
x , 0 , 0});
ll ret = 0;
while(s.size()){
Node u = s.top();
s.pop();
// 递归出口
if (u.x == 0 || u.x == 1) {
ret = 1;
continue;
}
if (u.state == 0){
// 递1阶段
s.push({
u.x , 0 , 1}); // 保存现场,等待递2阶段
s.push({
u.x - 1 , 0});
}else if (u.state == 1){
// 递2阶段
s.push({
u.x , ret , 2});
s.push({
u.x - 2 , 0 , 0});
}else{
ret += u.res;
}
}
return ret;
}
int main()
{
int x;
while (cin >> x) cout << f(x) << endl;
return 0;
}
2.求全排列
#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int maxn = 3e5 +5;
struct Node {
int state , ptr;
// state 代表递归阶段
// ptr 代表循环变量所指向的位置
};
void f (ll n , vector<string> &res){
stack<Node> s;
s.push({
1 , 1});
string a;
for (int i = 1 ; i <= n ; i++) a += to_string(i);
while(s.size()){
Node u = s.top();
s.pop();
if (u.state == n + 1) {
res.push_back(a);
continue;
}
if (u.ptr - 1 > u.state)
swap(a[u.state - 1] , a[u.ptr - 1 - 1]);
swap(a[u.state - 1] , a[u.ptr - 1]);
if (u.ptr + 1 <= n)
s.push({
u.state , u.ptr + 1});
s.push({
u.state + 1 , u.state + 1});
}
return ;
}
int main()
{
int x;
while (cin >> x) {
vector<string> res;
f(x , res);
cout << res.size() << endl;
}
return 0;
}
边栏推荐
- Word 样式模板复制到另一文档
- JVM知识脑图分享
- 2019陕西省省赛K-变种Dijstra
- Promise object and macro task, micro task
- wait()和sleep()的区别理解
- Recommend 10 learning websites that can be called artifact
- VMware Workstation fails to start VMware authorization service when opening virtual machine
- Gbdt source code analysis of boosting
- In depth: micro and macro tasks
- matlab--CVX优化工具包安装
猜你喜欢
随机推荐
Rediscluster setup and capacity expansion
matlab 优化工具 manopt 安装
spark中saveAsTextFile如何最终生成一个文件
ML - 自然语言处理 - 关键技术
Reflection - Notes
盒子躲避鼠标
HBCK fix problem
What is the Internet of things
Iframe nested other website page full screen settings
从 join on 和 where 执行顺序认识T-sql查询执行顺序
Spark SQL空值Null,NaN判断和处理
Spark002 --- spark task submission, pass JSON as a parameter
args参数解析
My creation anniversary
Spark partition operators partitionby, coalesce, repartition
Idea护眼色设置
See a lot of blinking pictures on apps, especially the member page
BPSK调制系统MATLAB仿真实现(1)
Instance Tunnel 使用
Idea remotely submits spark tasks to the yarn cluster









