递归与非递归转换(栈知识应用)

数据结构-栈、队列和数组 数据结构,栈,队列,数组 阅读详情

下面例题是一次作业中遇到的,很值得体味,与大家共享下。

 递归代码:

long f(long m,long n)
{
	long sum;
	if(m==0) sum=n+1;
	else if(n==0) sum=f(m-1,1);
	else k=f(m-1,f(m,n-1));
return sum;
}


 用递归来做很明了,当我们明白了递归所走的整个流程后,下面我们用栈来实现非递归的转换。

 非递归代码:

 

long f(long m,long n)
{
  listStack<long> k;    //用链栈来实现
  k.push(m);
  k.push(n);
  long sum;
 while(k.length()!=1)  //栈中只有一个元素时退出循环
  {
      n=k.pop();      //出栈 
       m=k.pop();
      if(m==0) k.push(n+1);
      else if(n==0)
      {
        k.push(m-1);
        n=1;
        k.push(n);
      }
      else
      {
        k.push(m-1);
        k.push(m);
        k.push(n-1);

      }
  }
  sum=k.pop();  
return sum;
}


 

数据结构:利用栈,将递归转换为非递归的方法 利用栈将递归转换为非递归 对于一般的递归过程,仿照递归算法执行过程中递归工作栈的状态变化,可直接写出相应的非递归算法。 步骤 第一次调用的参数push进堆栈,原有递归代码外层加一个while循环,判断条件就是递归结束的条件。递归调用的地方改成push(); continue; 直到遇到递归终止条件,退出递归运算所在循环,再用一个新的循环做出栈操作并计算,将递归代码中的return改成pop并执行响应的计算,直到栈空为止。就可以了。 完整描述: (1) 设置一个工作栈存放递归工作记录(包括实参、 返回地址 阅读详情

相关推荐

深入理解栈与队列在计算逻辑中的应用

本文通过详细的章节内容,探讨了栈和队列在编程和计算逻辑中的应用。内容涵盖递归过程的栈实现、非确定有限状态自动机(NFA)的接受问题以及命题逻辑中不同表达式的评估方法。文章深入解析了后缀、前缀和中缀表达式的转换与计算,并借助栈的深度优先遍历原理来解决这些问题。

weixin_35696112的博客 416

递归转化为栈

栈的迭代

hjxxxxx123491857的博客 651

如何用栈实现递归与非递归的转换

递归与非递归转换的基础知识是能够正确理解三种树的遍历方法:前序、中序和后序。第一篇就是关于这三种遍历方法的递归和非递归算法。

【数据结构与算法】递归转栈

前言 以前学数据结构学的很盲目,特别是后面学递归dp感觉脑子完全不够用,好像自己完全不是这块料一样。后来群里吹牛以及找各种资料发现能用递归的都可以用栈实现,递归本质是让系统帮你维护个栈,而你不递归,那么就自己手动维护栈,这样就能达到同样效果。 简单例题 leecode 144. 二叉树的前序遍历 输入: [1,null,2,3] 1 \ 2 / 3 输出: [1,2,3] 递归思路 var preorderTraversal = function(ro

不忘初心,坚定道路! 1030

爬取二手房数据:Python爬虫+Geopy实战,看透房价与地理位置的隐藏关系

哪些区域单价虚高(房源少但单价远高于周边);哪些小区性价比高(靠近地铁/学校,单价低于同地段平均水平);房价与地理位置的量化关系(如距离地铁每远1公里,单价下降多少)。如果想扩展分析范围,可爬取多个城市/区域的数据,对比不同城市的房价差异;或结合时间维度(定期爬取),分析房价的涨跌趋势。

专注于Python爬虫开发,分享爬虫技巧、项目实战与反爬经验,使用Scrapy、BeautifulSoup等工具,解决数据抓取难题。 949

超详细!动态规划详解分析(典型例题分析和对比,附源码)

为啥要使用动态规划?什么时候使用动态规划?以下是我的一些理解和心得,如果你感兴趣,就接着往下看吧。 对您有帮助的话记得给我点个赞哟! 动态规划的基本思想 动态规划(Dynamic Programming,DP)算法通常用于求解某种具有最优性质的问题。在这类问题中,可能会有许多可行解,每一个解都对应一个值,我们希望找到具有最优值的解。 动态规划算法与分治法类似,其基本思想也是将待求解的问题分解成若干个子问题,先求解子问题,然后从这些子问题的解中 得到原有问题的解。与分治法不同的是,动态规划经分解后得到的子问题

qq_44398094的博客 8万+

二叉树的遍历---递归转栈

二叉树的遍历 递归转栈的通用写法

Wzy000001的博客 1210

Sentence-BERT 语义相似度双塔模型

论文介绍 发表:2019,EMNLP 论文题目:《Sentence-BERT:sentence embeddings using siaese BERT-networks》 论文地址:https://arxiv.org/abs/1908.10084 Github:https://github.com/UKPLab/sentence-transformers 适用领域: 句向量生成 语义相似度计算 语义搜索 无监督任务(聚类) 1 概述 在20年之前的各种预训练模型中,比如bert,XLNet,Alb

weiyaner的博客 9194

26考研——栈、队列和数组_栈(3)

26考研408数据结构——栈、队列和数组,持续更新ing

主攻整理408、专升本资料~ 1690

极验滑块验证码破解与研究(一):AST还原混淆JS

极验滑块验证码破解与研究(一):AST还原混淆JS声明一、环境安装1. node安装1.1. node下载1.2. 配置环境变量1.3. node安装检测1.4. pycharm配置node环境2. babel库安装2.1. babel库安装命令2.2. babel库安装检测二、AST还原混淆JS1. 模块导入2. AST还原流程3. 复制还原需要用到的js源码4. AST还原函数详解4.1. replace_unicode4.2. replace_unicode, replace_name_array,

帯泪的鱼的博客 1万+

(学习笔记)机器人自主导航从零开始第四步———Rviz、Gazebo、Meshlab的安装

一、Rviz的安装 Rviz是一个

qq_59475883的博客 5057

【数据结构】五、栈

【数据结构】五、栈

lieam的博客 779

同态加密与SEAL库实战:CKKS参数调优避坑指南

本文深入探讨了同态加密技术中CKKS方案的参数调优实践,重点解析了SEAL库中`poly_modulus_degree`、`coeff_modulus`和`scale`三大核心参数的配置技巧与避坑指南。通过实战案例展示了如何平衡计算深度、精度与性能,为开发者提供了一套完整的参数优化方法论,帮助避免常见的'scale out of bounds'等错误,显著提升同态加密应用的可靠性和效率。

weixin_29315569的博客 230

数据结构-栈和队列篇

栈和队列思维导图+栈和队列习题

qq_44663230的博客 2951

人工智能训练师三级考试备考全攻略|报名条件+真题+补贴申领一站式通关(2026版)

本专栏是人工智能训练师三级考证最完整的备考指南,共77篇文章,覆盖从职业认知、报名实操、AI基础知识、数据标注、模型训练测试部署、考前冲刺到考后进阶的全链路。本导读按模块整理了全部文章链接,帮你快速定位所需内容。人工智能训练师是国家认定的正式职业,证书可在osta.mohrss.gov.cn查询,三级证书可申领最高3120元技能补贴。

白话机器学习 1800

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

【数据结构】汇总三、栈和队列

栈(Stack)是只允许在一端进行插入或删除操作的线性表。重要术语:栈顶(现在能放入的一段),栈底(最早放入的元素的一段),空栈。逻辑结构:与普通线性表相同数据的运算:插入、删除操作有区别InitStack(&S):初始化栈。构造一个空栈S,分配内存空间。DestroyStack(&L):销毁栈。销毁并释放栈 S 所占用的内存空间。Push(&S,x):插入,进栈。若栈S未满,则将x加入使之成为新栈

关注:https://github.com/Suhan42 1453

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

栈

栈一、栈的概述1.1 什么是栈1.2 出栈(pop)和入栈(push)的理解1.3 栈的应用1.3.1 子程序的调用:1.3.2 处理递归调用:1.3.3 表达式的转换:1.3.4 二叉树的遍历1.3.5 图形的深度优先(depth一first)搜索法二、数组模拟栈三、栈实现综合计算器 一、栈的概述 1.1 什么是栈 栈的英文为(stack) ,栈是一个先入后出(FILO-First In Last Out)的有序列表。 栈(stack)是限制线性表中元素的插入和删除只能在线性表的同一端进行的一种特殊线性

weixin_43956763的博客 866

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

栈(前缀、中缀、后缀表达式、递归)Stack

三、栈(Stack) 1、栈的概念 ​ 栈与队列相反,队列是在队头进入,队尾出队的线性表,栈是仅能在栈顶进行插入和删除的线性表(先入先出)。我们通常把允许插入和删除的一端成为栈顶,另一端称为栈底。栈的插入操作为入栈,栈的删除操作为出栈,不含任何数据元素的栈称为空栈。 栈的表示: 用数组模拟栈 用链表模拟栈 2、栈的应用场景 前缀、中缀和后缀表达式 前缀表达式是运算符在前,数字符在后 (...

Simon郎的博客 2151

2.数据结构-栈和队列

即栈的顺序存储结构是利用一组地址连续的存储单元依次存放自栈底到栈顶的数据元素,同时附设指针top指示栈顶元素在顺序栈中的位置。通常的习惯做法是top=0表示空栈,鉴于C语言中数组的下标约定从0开始,则当以C作描述语言时,如设定会带来很大不便;另一方面,由于栈在使用过程中所需最大空间的大小很难估计,一般来说,在初始化设空栈时不应限定栈的最大容量。先分配一个基本容量,然后在应用过程中,当栈的空间不够使用时再逐段扩大。,因此,对栈来说,表尾端有其特殊含义,称为。和线性表类似,栈也有两种存储表示方式。

qq_62224565的博客 824

数据结构 第三章 栈和队列(栈)

2、进栈是指在栈顶位置插入元素(也叫入栈或者压栈),出栈是指删除栈顶元素(也叫弹栈或者退栈)假定表达式中只有运算符和操作数两类成分,运算符有(+、-、*、/)和圆括号()6、顺序栈:使用数组的后端表示栈顶,top常被使用为栈顶指针。1、栈顶是指允许进行插入和删除操作的一端,另外一端称为栈底。运算符栈(OperatorStack)SY。操作数栈(OperandStack)SC。4、空栈是指不含有元素的空表。

一路生花 2025

计算机数组的知识点,考研计算机学操作系统知识点:栈、队列和数组

考生应该都知道,考研计算机学知识点多也难,但是现阶段考研计算机专业的人数非常火爆,甚至是文科学生跨专业报考都会选择计算机。那么考研计算机学该复习哪些重要知识点呢,下面是海天考研网整理的关于考研计算机学操作系统中进程的状态与转换知识点。一起来复习吧~1.栈、队列的定义及其相关数据结构的概念,包括:顺序栈、链栈、循环队列、链队列等。栈与队列存取数据(请注意包括:存和取两部分)的特点。2. 掌握顺序栈和...

weixin_39636707的博客 248

栈与队列.

scanf :当遇到回车,空格和tab键会认为输入结束,但是回车,空格和tab键仍会留在输入的缓冲区中。中缀表达式直接求值其实就是 在中缀表达式转后缀 的基础上,把运算符进入表达式的时候直接弹出两个数计算之后再压入表达式,最后表达式中只有一个数字就是结果。一开始提交的时候出现了超栈的情况,由于栈顶指针初值为0,第一个是右括号时会出现zhan[-1]的情况,把top初值改为1后就成功通过了。关于中缀表达式,后缀表达式这类问题,里面涉及到一些输入问题,之前也因为输入问题被卡过,大一的时候学过但是现在都忘记。

m0_56533544的博客 172

计算机队列概念,2020计算机专业考研数据结构知识点:栈、队列和数组

2020计算机专业考研数据结构知识点:栈、队列和数组1.栈、队列的定义及其相关数据结构的概念,包括:顺序栈、链栈、循环队列、链队列等。栈与队列存取数据(请注意包括:存和取两部分)的特点。2. 掌握顺序栈和链栈上的进栈和退栈的算法,并弄清栈空和栈满的条件。注意因栈在一端操作,故通常链栈不设头结点。3. 如何将中缀表达式转换成前缀、后缀表达式,了解对两种表达式求值的方法。4. 栈与递归的关系。用递归解...

weixin_42537499的博客 393
下一篇: 理解关于java反射中类的域及修饰符
云贤力
博客等级 码龄15年 3粉丝 15原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值