递归函数溢出 [英] Recursive function overflow

查看:118
本文介绍了递归函数溢出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,我构建了一个有效的递归函数,该函数可找到两个字符串之间的最长公共序列.
http://en.wikipedia.org/wiki/Longest_common_subsequence_problem [

Hey, I built a working recursive function that finds the Longest Common Sequence between two strings.
http://en.wikipedia.org/wiki/Longest_common_subsequence_problem[^]
It works perfectly fine and it is fast cause I use a memiozation table so that I''m not calling something that I''ve previously called already. My problem lies that when I have strings over 150 characters, I get a call stack overflow. I was wondering if anyone knows of a good suggestion to fixing this or of a better way of finding the longest common subsequence.

推荐答案

当计算机的堆栈获得太多的函数调用时,就会发生堆栈溢出,因此,超过150个字符的字符串会产生此类错误.您可以使用几种解决方法来解决此问题:
1)优化代码以减少函数调用
2)使用Stack对象以通过存储变量状态来模拟递归调用
3)最好的-考虑一种非递归算法.这是一个常见的面试问题,无需使用递归即可找到解决方案.有整篇文章专门讨论最长公共序列的问题,
此处 [
Hi,
stack overflow happens when your computer''s stack gets too many function calls, thus strings over 150 chars generate such error. There are several workarounds that you can use in order to solve this problem:
1) optimize your code to get fewer function calls
2) use Stack object in order to simulate recursive calls, by memorizing variable states
3) the best one - think of an algorithm that is not recursive. Its a common interview question, to find a solution without the use of recursion. There is an entire article devoted to the problem of Longest Common Sequence here[^] at codeproject. But before looking at it, I suggest you to try finding the non-recursive solution by your own.
Regards


这篇关于递归函数溢出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆