Logo
Section 1 / 6

迭代

本课程介绍了迭代的基础知识。

导入

迭代

本课程介绍了迭代的基础知识。

什么是迭代?

迭代代码 是一段在 循环 中运行的代码块。换句话说,相同的代码会反复执行多次。其思想与递归类似。

当你对递归概念逐渐熟悉后,解决实际问题时可能不再频繁使用迭代,但确实存在一些场景下迭代仍然非常有价值。此外,迭代也是理解递归的一个简单入门方式,因为我们已经掌握了如何遍历数组和列表。递归本质上是将同样的思路向前推进,但做了一些调整。

例如:

  • 逆序打印链表
  • 计算一个数的阶乘
  • 斐波那契数列
  • 需要动态使用多个循环的问题

迭代的概念图示

Course Image

示例

下面的代码片段展示了计算 一个数的阶乘 的迭代版本和递归版本。

迭代版本

1class MainClass { 2 3 private static int factorialIterative(int n) { 4 5 int factorialResult = 1; 6 7 for (int i = 1; i <= n; i++) { 8 factorialResult = factorialResult * i; 9 } 10 return factorialResult; 11 12 } 13 14 public static void main( String args[] ) { 15 int result = factorialIterative(5); 16 System.out.println("阶乘结果为: " + result); 17 } 18}

递归版本

1class MainClass { 2 3 private static int factorialRecursive(int n) { 4 5 if (n == 1) { 6 return 1; 7 } 8 else { 9 return (n * factorialRecursive(n-1)); 10 } 11 12 } 13 14 public static void main( String args[] ) { 15 int result = factorialRecursive(5); 16 System.out.println("阶乘结果为: " + result); 17 } 18}

通常情况下,只要需要使用循环,就可以考虑用递归方法来替代。

递归基础

递归与迭代