<栈模拟递归>

2023大厂真题提交网址(含题解):

www.CodeFun2000.com(http://101.43.147.120/)

最近我们一直在将收集到的机试真题制作数据并搬运到自己的OJ上,供大家免费练习,体会真题难度。现在OJ已录入50+道2023年最新大厂真题,同时在不断的更新。同时,可以关注"塔子哥学算法"公众号获得每道题的题解。
在这里插入图片描述

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值