除了生成斐波那契数列之外,还有什么递归的好例子?

发布于 2024-10-17 03:48:56 字数 364 浏览 6 评论 0原文

可能的重复:
现实世界中的递归示例
递归函数示例

我发现大多数编程语言教程都通过使用一个简单的示例来教授递归,即如何生成斐波那契数列,我的问题是,除了生成斐波那契数列之外,还有另一个很好的例子来解释递归是如何工作的吗?

Possible Duplicates:
Real-world examples of recursion
Examples of Recursive functions

I see that most programming language tutorial teach recursion by using a simple example which is how to generate fibonacci sequence, my question is, is there another good example other than generating fibonacci sequence to explain how recursion works?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(23

痴梦一场 2024-10-24 03:48:57

检查回文

bool recursivePalindrome(std::string str, unsigned int index = 0) {
    if (index > str.length()/2) return true;
    else if (str[index] == str[str.length()-index-1])
        return recursivePalindrome(str, ++index);
    else return false;
}

或者不太严重的注释:)

void StackOverflow()
{
   StackOverflow();
}

Check for a palyndrome:

bool recursivePalindrome(std::string str, unsigned int index = 0) {
    if (index > str.length()/2) return true;
    else if (str[index] == str[str.length()-index-1])
        return recursivePalindrome(str, ++index);
    else return false;
}

Or on a less serious note :)

void StackOverflow()
{
   StackOverflow();
}
逆蝶 2024-10-24 03:48:57

求阶乘怎么样。

int GetFactorial(int n )
{
  if ( n==0) return 1;
  return n*GetFactorial(n-1);
}

这个想法是,阶乘被递归地定义为 n 和 (n-1) 阶乘的乘积。从递归定义中,你可以得到递归。

How about finding factorial.

int GetFactorial(int n )
{
  if ( n==0) return 1;
  return n*GetFactorial(n-1);
}

The idea is, factorial is defined recursively as the product of n and factorial of (n-1). And from recursive definition, you get your recursion.

囍笑 2024-10-24 03:48:57

遍历作为文件系统一部分的目录树的文件夹层次结构是一个很好的实际示例。查看此 SO 帖子中的 C++ 示例:

为什么我在递归删除目录时遇到问题?

Traversing the folder hierarchy of a directory tree as part of a file system is a good real-world example. Look into this SO post for a C++ example:

Why am I having problems recursively deleting directories?

救赎№ 2024-10-24 03:48:57
  • 这里给出的大多数其他例子都是数学例子,它们实际上只是重新说明了递归的相同应用。
  • 搜索和排序变体是很好的算法示例,但对于初学者来说通常有点太复杂。
  • 河内塔是一部经典作品,但确实很做作。

================

我用来演示递归的简单威力的示例是目录树中的递归文件处理。

这是一个 C# 示例

void ProcessFiles( string sFolder )
{
    foreach( string f in Directory.GetFiles( sFolder ) )
    {
        DoSomethingTo( f );
    }
    foreach( string d in Directory.GetDirectories( sFolder ))
    {
        ProcessFiles( d );
    }
}
  • Most of the other examples given here are mathematics examples which really just re-illustrate the same application of recursion.
  • The search and sort variants are good algorithm examples but often a bit too complicated for beginners.
  • Towers of Hanoi is a classic but pretty contrived really.

================

The example I use for demonstrating the simple power of recursion is recursive file processing in a directory tree.

Here is a C# example

void ProcessFiles( string sFolder )
{
    foreach( string f in Directory.GetFiles( sFolder ) )
    {
        DoSomethingTo( f );
    }
    foreach( string d in Directory.GetDirectories( sFolder ))
    {
        ProcessFiles( d );
    }
}
我只土不豪 2024-10-24 03:48:57

合并排序是一个很好的算法示例,当递归实现时更容易阅读和理解。

这是合并排序的一个高级伪代码版本:

def merge_sort(List sortlist)
    if sortlist.length <= 1 return sortlist
    split sortlist into leftlist and rightlist
    return merge(merge_sort(leftlist), merge_sort(rightlist))   

def merge(List leftlist, List rightlist)
    while(leftlist and rightlist not empty)
        compare leftlist.first to rightlist.first
        pop lowest value off its list and append to resultlist
    append any remains of leftlist onto resultlist
    append any remains of rightlist onto resultlist
    return resultlist

它的迭代版本的编写和可视化要复杂得多。

Merge sort is a pretty good example of an algorithm that is easier to read and understand when implemented recursively.

Here's a little high-level pseudocode version of Merge Sort:

def merge_sort(List sortlist)
    if sortlist.length <= 1 return sortlist
    split sortlist into leftlist and rightlist
    return merge(merge_sort(leftlist), merge_sort(rightlist))   

def merge(List leftlist, List rightlist)
    while(leftlist and rightlist not empty)
        compare leftlist.first to rightlist.first
        pop lowest value off its list and append to resultlist
    append any remains of leftlist onto resultlist
    append any remains of rightlist onto resultlist
    return resultlist

An iterative version of this is would be much more complicated to write and to visualise.

扛刀软妹 2024-10-24 03:48:57

有几个示例:

加泰罗尼亚数字

T(n) = Sum(T(i)*T(n-i)) for all 1 <= i < n

阿克曼函数

A(x,y) = y+1 (if x = 0)
A(x,y) = A(x-1,1) (if y=0)
A(x,y) = A(x-1, A(x,y-1)) otherwise.

简单迷宫问题 >

寻找哈密顿路径问题

阶乘。

您可以查看 wiki 页面以获取其他参考。

There are several samples:

Catalan numbers:

T(n) = Sum(T(i)*T(n-i)) for all 1 <= i < n

Ackermann function:

A(x,y) = y+1 (if x = 0)
A(x,y) = A(x-1,1) (if y=0)
A(x,y) = A(x-1, A(x,y-1)) otherwise.

Simple Maze problem

Finding Hamiltonian Path problem

factorial.

and you can see wiki page for other references.

枉心 2024-10-24 03:48:57

递归的好例子通常与底层数据结构或问题本身是递归的情况相关:树、图、使用分而治之方法的算法(如许多排序)、递归语法的解析器(如常见的算术表达式)、查找策略类似国际象棋的两人游戏(举个简单的例子,考虑一下 Nim)、组合问题等。

Good examples of recursion are often related to cases where underlying data structure or the problem itself is recursive : trees, graphs, algorithms using divide and conquer approach (like many sorts), parser of recursive grammars (like common arithmetic expresions), find strategy for chess-like two players games (for a simple exemple consider Nim), combinatory problems, etc.

娇纵 2024-10-24 03:48:57

尝试递归二分搜索:
http://www.fredosaurus.com/notes-cpp/algorithms/searching /rbinarysearch.html

或者递归快速排序:
http://www.dreamincode.net/forums/topic/72311- recursive-quicksort-algorithm/

这些只是递归函数的广阔世界中的两个小例子。

Try recursive binary search:
http://www.fredosaurus.com/notes-cpp/algorithms/searching/rbinarysearch.html

Or a recursive quick sort:
http://www.dreamincode.net/forums/topic/72311-recursive-quicksort-algorithm/

These are just two small example in a vast world of recursive functions.

你爱我像她 2024-10-24 03:48:57

算术表达式的计算可以使用堆栈递归或迭代地完成。比较这两种方法非常有启发性。

Evaluation of arithmetic expressions can be done recursively or iteratively using a stack. It can be quite instructive to compare the two approaches.

装迷糊 2024-10-24 03:48:57

我记得我通过编写一个程序来理解递归,该程序搜索单词梯子。在给定的字典中。

I remember that I understood recursion by writing a programm, that searches for word ladders. In a given dictionary.

記憶穿過時間隧道 2024-10-24 03:48:57

我的岳母参加了 C 语言的入门课程。她有一个家庭作业问题,比如:

你有一根金属条(长度为len)和一个数字
将金属切割成的订单数 (n)
各种长度。你想要最大化
所使用的金属量,但是
不能超过总长度。

讲师建议以二进制形式从 1 迭代到 2**n,如果相应位为 0,则排除一个订单,如果相应位为 1,则包括一个订单,同时跟踪最大和。他的提议将在多项式时间内运行。

另一种解决方案是使用递归背包算法。您可以从 len 向下迭代到 1 并进行深度优先搜索以递归地查找长度之和。

我使用递归的另一个领域是 Huffman 编码(用于压缩字符串),但是这没有背包问题的直观感受。

递归是一个完全不同的奇妙概念。祝愿您学习或教授它。

My mother-in-law took an introductory course in C. She had a homework problem, something like:

You have a bar of metal (length len), and a number
of orders (n) to cut the metal into
various lengths. You want to maximize
the amount of metal being used, but
cannot exceed the overall length.

The instructor suggested iterating from 1 to 2**n in binary, excluding an order if its corresponding bit were 0 and including an order if its bit were 1, while keeping track of the maximum sum. His proposal would run in polynomial time.

Another solution exists using a recursive knapsack algorithm. You can iterate down from len to 1 and do a depth-first search to recursively find the sum of lengths.

A different area in which I have used recursion was for Huffman coding (for compressing a string), but this does not have the intuitive feel of the knapsack problem.

Recursion is a wonderful concept that is radically different. Best wishes in learning or teaching it.

别闹i 2024-10-24 03:48:57

阿克曼函数:

/* undefined if m and n are negative */
uint32 ackermann( uint32 m, uint32 n )
{
  if( m < 0 && n < 0 ) { exit(1); /* invalid m and n */ }

  if( m == 0 ){ return n + 1; }

  if( m > 0 && n == 0 ){ return ackermann( m - 1, 1 ); }

  if( m > 0 && n > 0 ){ return ackermann( m - 1, ackermann(m, n - 1) ); }
}

m > 的多重比较0 是多余的(并且可以简化)。然而,让它们保持原样,会显示阿克曼函数的标准定义。

但人们不必脱离数学边缘那么远就能找到除斐波那数之外的有趣的递归函数。

您拥有最大公约数 (GDC) 函数、快速排序和始终典型的二分搜索算法。

Ackermann function:

/* undefined if m and n are negative */
uint32 ackermann( uint32 m, uint32 n )
{
  if( m < 0 && n < 0 ) { exit(1); /* invalid m and n */ }

  if( m == 0 ){ return n + 1; }

  if( m > 0 && n == 0 ){ return ackermann( m - 1, 1 ); }

  if( m > 0 && n > 0 ){ return ackermann( m - 1, ackermann(m, n - 1) ); }
}

The multiple comparisons of m > 0 are redundant (and can be simplified). Leaving them as-is, however, shows the standard definition of the Ackermann function.

But one does not have to go so far off the mathematical edge to find interesting recursive functions other than the Fibonnaci numbers.

You have the greatest common denominator (GDC) function, quicksort and the always typical binary search algorithm.

苦妄 2024-10-24 03:48:57

任何事物都具有层次结构。
例如列出你老板下面的所有员工。

Anything which has a hierarchy.
For example listing all the employees beneath your boss.

心不设防 2024-10-24 03:48:57

递归在数学归纳法中找到了基础,并且应该这样教授。

通过列表处理可以清楚地暴露通过归纳法定义的函数。关于 fold 有很多话要说例如。

然后,转向树木。

Recursion finds its fundations in mathematical induction, and should be taught as such.

Defining functions by induction can be exposed clearly with list processing. There are many things to say about fold for instance.

Then, move on to trees.

不如归去 2024-10-24 03:48:57

显然,它不是 C++,但概念很合理:

PHP 递归遍历嵌套多维数组:

public function recurse_me($collection) {
    foreach ($collection as $value) {
        if (is_array($value)) {
            $this->recurse_me($value);
        } else {
            // process value.
        }
    }
}

It's not C++, obviously, but the concept is sound:

PHP recursively traversing nested multidimensional arrays:

public function recurse_me($collection) {
    foreach ($collection as $value) {
        if (is_array($value)) {
            $this->recurse_me($value);
        } else {
            // process value.
        }
    }
}
青萝楚歌 2024-10-24 03:48:57

学术上的例子是阶乘

n!

计算。
在现实生活中,你会得到数学库。

The academic example is the factorial

n!

calculum.
In real life, you get math libs.

天气好吗我好吗 2024-10-24 03:48:57

有些排序算法依赖于递归。

然后,还有使用递归实现的二分搜索

There are sorting algorithms that rely on recursion.

And then, there's the binary search that is implemented with recursion.

顾铮苏瑾 2024-10-24 03:48:57

堆排序也是一个很好的例子。你可以在 Cormen、Rivest 等人的《算法导论》中阅读相关内容。很棒的书,我希望你会从中发现很多有趣的东西。

Heap sort is also a good example. You can read about it in "Introduction to Algorithms" by Cormen, Rivest and others. Great book, I hope you'll find a lot of interesting there.

蓝戈者 2024-10-24 03:48:57

链接节点类型结构上的许多操作可以是递归的。其他人提到了 BST,但如果您不想解释它们是什么,请考虑在线性、未排序的列表中搜索最高值:

int MaxValue(Node node)
{
    if (node == null)
        return 0;

    if (node.Next == null)
        return node.Value;

    int maxNext = MaxValue(node.Next);
    return node.Value > maxNext ? node.Value : maxNext;
}

列表(在本例中为链接列表)在实际中非常容易解释 -世界术语;您的观众甚至不必具有编程背景。您可以简单地将其描述为一组未排序的框或数字列表。

Lots of operations on linked-node type structures can be recursive. Others have mentioned BSTs, but if you don't want to have to explain what those are, consider searching for the highest value in a linear, unsorted list:

int MaxValue(Node node)
{
    if (node == null)
        return 0;

    if (node.Next == null)
        return node.Value;

    int maxNext = MaxValue(node.Next);
    return node.Value > maxNext ? node.Value : maxNext;
}

Lists (in this case, linked lists) are very easy to explain in real-world terms; your audience doesn't even have to have a programming background. You can simply describe it as a group of unsorted boxes, or a list of numbers.

冰雪梦之恋 2024-10-24 03:48:56

经典的是二叉树搜索:

def findval (node,val):
    if node == null:
        return null
    if node.val = val:
        return node
    if node.val > val:
        return findval (node.left,val)
    return findval (node.right,val)

findval (root,thing_to_find)

这可能比简单的公式复杂一点,但它是递归的“面包和黄油”使用,并且它说明了使用它的最佳位置,即递归级别最小化的地方。

我的意思是:您可以添加两个非负数:

def add (a,b):
    if b == 0:
        return a
    return add (a+1,b-1)

但是您会发现自己很快就用完了大数字的堆栈空间(当然,除非编译器优化了尾端递归,但对于您所关心的教学水平,您可能应该忽略这一点)。

The classic is the binary tree search:

def findval (node,val):
    if node == null:
        return null
    if node.val = val:
        return node
    if node.val > val:
        return findval (node.left,val)
    return findval (node.right,val)

findval (root,thing_to_find)

That may be a little more complex than a simple formula but it's the "bread and butter" use of recursion, and it illustrates the best places to use it, that where the recursion levels are minimised.

By that I mean: you could add two non-negative numbers with:

def add (a,b):
    if b == 0:
        return a
    return add (a+1,b-1)

but you'd find yourself running out of stack space pretty quickly for large numbers (unless the compiler optimised tail-end recursions of course, but you should probably ignore that for the level of teaching you're concerned with).

太傻旳人生 2024-10-24 03:48:56

其他答案提到了各种算法,这完全没问题,但是如果您想要更多“具体”示例,您可以列出某个目录及其子目录中的所有文件。分层文件系统是递归(树)结构的一个众所周知的示例,您可以使用这个具体示例来显示深度优先和广度优先搜索。

The other answers mention various algorithms, which is completely fine, but if you want a bit more "concrete" example, you could list all files in some directory and its subdirectories. The hierarchical file system is a well-known example of a recursive (tree) structure, and you could show depth-first and breadth-first search using this concrete example.

昨迟人 2024-10-24 03:48:56

我最喜欢的递归示例是 河内塔:从杆子上移动一堆棋子A 到杆 B,将最低棋子上方的所有棋子移动到非 A 或 B 的杆子,然后将最低的棋子移动到 B,然后将放在最低棋子顶部的“辅助杆”上的堆栈移动到片。对于第一步和第三步,您将递归地遵循此说明。请参阅链接以获得更长的解释:)

My favourite example for recursion is the Towers of Hanoi: To move a stack of pieces from pole A to pole B, you move everything above the lowest piece to the pole that is not A or B, then move the lowest piece to B, and then you move the stack that you put on the "helper pole" on top of the lowest piece. For the first and third step, you follow this instruction recursively. See the link for a longer explanation :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文