首页 > Java > java教程 > 正文

Java 中的递归

WBOY
发布: 2024-08-30 15:33:33
原创
276 人浏览过

Java中的递归被定义为“一个方法直接或间接地连续调用自身(同一个方法)”。递归函数用于需要一次又一次执行同一组操作直到得出结果的情况。它执行多次迭代,并且每次迭代问题陈述都变得越来越简单。 java中的递归是一种基于同一问题的较小块的解来解决问题的方法。大多数无限可能的迭代都可以通过递归来解决。我们可以说递归是循环语句的另一种方法。如果我们没有正确使用递归函数,那么它会执行无限次。

语法:

广告 该类别中的热门课程 JAVA 掌握 - 专业化 | 78 课程系列 | 15 次模拟测试
returntype methodName()
{
//logic for application
methodName();//recursive call
}
登录后复制
登录后复制

我们如何停止 Java 中的无限递归条件?

要停止无限条件,我们必须满足以下条件:

  • 基本条件: 指定内部条件是否停止递归函数。
  • 递归调用: 正确的递归调用。

我们可以通过两种方式调用递归函数:

1。直接递归调用

如果我们从内部方法体调用相同的方法。

语法:

returntype methodName()
{
//logic for application
methodName();//recursive call
}
登录后复制
登录后复制

示例:

数字的阶乘是直接递归的一个例子。递归的基本原理是通过将复杂问题分解为更小的问题来解决它。例如,对于一个数字的阶乘,如果我们知道“i-1”的阶乘,我们就可以计算“i”的阶乘。

代码:

public class Factorial {
static int fact(int i){
if (i == 1)
return 1;
else
return(i * fact(i-1));
}
public static void main(String[] args) {
System.out.println("The factorial of given number 6 is: "+fact(6));
}
}
登录后复制

输出:

Java 中的递归

2。间接/相互递归调用

如果我们从另一个方法调用一个方法,并且从第一个方法调用另一个方法,反之亦然。

语法:

<firstIndirectRecursive()
{
// Logic
secondIndirectRecursive();
}
secondIndirectRecursive()
{
//Logic
firstIndirectRecursive();
}
登录后复制

示例:

为了显示间接递归,我们使用以下程序来根据给定的输入找出给定的数字是偶数还是奇数。

代码:

import java.util.Scanner;
public class IndirectRecursion {
public static boolean oddNum(int i) {
if (i<0) throw new IllegalArgumentException("Number is negative");
if(i == 0){
return false;
} else {
return evenNum(i-1);
}
}
public static boolean evenNum(int i) {
if (i<0) throw new IllegalArgumentException("Number is negative");
if(i == 0){
return true;
} else {
return oddNum(i-1);
}
}
public static void main(String[] args) {
Scanner inputNum = new Scanner(System.in);
System.out.print("Give a number: ");
int n = inputNum.nextInt();
if (evenNum(n)) System.out.println(n + " is even");
else System.out.println(n + " is odd");
inputNum.close();
}
}
登录后复制

输出:

Java 中的递归

Java 中的递归示例

这里还有一些使用递归方法解决问题的示例。

示例 #1 – 斐波那契数列

如果 number3=number1+number2,即每个数字都是其前两个数字之和,则称一组“n”个数字位于斐波那契数列中。因此,序列总是从前两位数字开始,如 0 和 1。第三个数字是 0 和 1 的和,结果是 1,第四个数字是 1 和 1 相加,结果是 2,序列继续。

查看以下 Java 代码来生成斐波那契数列:

代码:

public class FibonacciSeries{
static int num1=0,num2=1,num3=0;
static void fibonacci(int n){
if(n>0){
num3 = num1 + num2;
num1 = num2;
num2 = num3;
System.out.print(" "+num3);
fibonacci(n-1);
}
}
public static void main(String args[]){
int n=10;
System.out.print(num1+" "+num2);//printing constant first two digits 0 and 1
fibonacci(n-2);//Since first two numbers are already done
}
}
登录后复制

输出:

Java 中的递归

这里前两个数字被初始化为 0 和 1 并打印。变量“num1”、“num2”和“num3”用于生成所需的序列。变量“num3”是“num1”和“num2”相加得到的,数字通过打乱的方式向左移动一位,如代码所示。这里递归调用函数“Fibonacci”,每次迭代时,“n”的值减 1。因此,一旦“n”达到值 0,递归就会退出。

示例 #2 – 河内塔

这是一个经典的数学问题,有 3 个极点和“n”个不同大小的圆盘。谜题如下:

Java 中的递归

一开始,第一个杆子的圆盘排列方式是最大的圆盘位于杆的底部,最小的圆盘位于杆的顶部。目标是将这些圆盘从第一个极移动到第三个极,使圆盘保持与第一个极相同的位置。以下是移动这些磁盘时需要记住的一些条件:

  • 一次只需移动一个磁盘。
  • 在此过程中,不允许将较大的磁盘放在较小的磁盘上。
  • 第二根(中间)杆可以用来调解,同时将圆盘从第一根杆转移到第二根杆。

以下是可用于解决该难题的Java代码:

代码:

public class TowerOfHanoi {
public static void main(String[] args) {
int count = 3;
tower(count, 'A', 'B', 'C');
}
public static void tower(int first, char disk1, char temp, char disk2) {
if (first == 1) {
System.out.println("Disk 1 from " + disk1 + " to " + disk2);
} else {
tower(first - 1, disk1, disk2, temp);
System.out.println("Disk " + first + " from " + disk1 + " to " + disk2);
tower(first - 1, temp, disk1, disk2);
}
}
}
登录后复制

输出:

Java 中的递归

Here the variable “count” represents the number of discs to be used. The function “tower” is the recursive function used to move the discs from rod 1 to rod 3. A simple solution to this problem can be provided by considering 2 discs at first.

  • First, we start by moving disc1 from rod 1 to rod 2.
  • Next, we move disc2 to rod 3.
  • Finally, we finish by moving disc1 to rod 3, completing the required solution.

This same principle is applied for the “n” number of discs by moving (n-1)the disc from rod 1 to 2 and following similar steps as above.

Example #3 – Factorial of Number

Code:

package com.recursion;
import java.util.Scanner;
public class FactorialOfNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Which number factorial do you want?=>");
//taking input from the user
int input = scanner.nextInt();
System.out.println("Factorial of " + input + "! is=>"+getMyFactorialNumber(input));
scanner.close();
}
public static long getMyFactorialNumber(int inputNumber) {
if (inputNumber == 1)//base condition
return 1;
return inputNumber * getMyFactorialNumber(inputNumber - 1);//recursive call
}
}
登录后复制

Output:

Java 中的递归

Example #4 – Armstrong Number

Code:

import java.util.Scanner;
//ARMSTRONG number means sum of numbers of cubes equal to the number
public class ArmstrongNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter any Number?=>");
// taking input from the user
int input = scanner.nextInt();
//calling isArmstrongNumber() method and put in a variable
double checkNumber=isArmstrongNumber(input);
//checking the number
if(input==checkNumber)
{
System.out.println(input+" is ARMSTRONG NUMBER");
}
else
{
System.out.println(input+" not is ARMSTRONG NUMBER");
}
scanner.close();
}
static int remainderNumber;
static double total = 0;
public static double isArmstrongNumber(int inputNumber) {
if (inputNumber > 0) {
remainderNumber = inputNumber % 10;//separating digits
total = total + Math.pow(remainderNumber, 3);//cubes sum
isArmstrongNumber(inputNumber / 10);//recursive call
}
return total;
}
}
登录后复制

Output:

Java 中的递归

Example #5 – Palindrome Number

Code:

import java.util.Scanner;
public class PalindromeNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter any Number=>");
// taking input from the user
int input = scanner.nextInt();
int checkNumber = palindromeNumberOrNot(input,0);
if (checkNumber == input)
{
System.out.println(input+" is a PALINDROME NUMBER");
}
else
{
System.out.println(input+" is not a PALINDROME NUMBER");
}
scanner.close();
}
public static int palindromeNumberOrNot(int inputNumber,int baseNumber) {
if (inputNumber == 0)// base case
return baseNumber;
baseNumber = (baseNumber * 10) + (inputNumber % 10);// getting the reverse of the number and stores in temp
return palindromeNumberOrNot(inputNumber/10,baseNumber);//recursive call
}
}
登录后复制

Output:

Java 中的递归

Java 中的递归

Conclusion

Recursive functions are relatively simpler to code, but they are also not that efficient as compared to the other existing methods. Hence they are majorly used in cases where the time given for development is less and also where a significant pattern can be observed in the problem.

以上是Java 中的递归的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:php
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!