search
HomeComputer TutorialsComputer KnowledgeI would like to ask everyone for a detailed explanation of the recursive algorithm in java.

I would like to ask everyone for a detailed explanation of the recursive algorithm in java.

Jan 07, 2024 pm 12:14 PM
Recursive algorithm in jaI would like to ask you for more details on the recursive algorithm in java.Using recursive method in java to get n numbers without duplication

I would like to ask you for a detailed explanation of the recursive algorithm in java

public class Test{

public static int getResult(int parameter) {

if (parameter == 0) { return result; } else { result *= parameter; return recursiveFunction(parameter - 1, result); }

return number;

}

public static void main(String[] args) { //Write your code here }

int result = result(5);

System.out.println(result);

}

}

Its execution principle is as follows:

result(5) Initially, enter the function body to determine whether parameter is less than or equal to 1. At this time, parameter is equal to 5 and the condition is not established. Execute parameter*result(parameter-1), that is, 5 * result(5-1), the program Execute repeatedly...

5*result(5-1)

4*result(4-1)

3*result(3-1)

2 * result(2 - 1) At this point, parameter is equal to 1 and meets the condition. The function returns 1 and returns layer by layer. Right now:

result(1) =1

2*result(1)=2*1=2

3*result(2)=3*2=6

4*result(3)=4*6=24

5*result(4)=5*24=120

Using recursive method in java to completely arrange n numbers without duplication n 3

The program is as follows, the input format is:

5

3 1 2 1 2 means that the first line is a number, indicating the number of numbers to be entered next. The second line has n numbers, representing the numbers to be sorted. The input assumes that the numbers to be sorted are all non-negative numbers.

import java.io.File;

import java.io.FileNotFoundException;

import java.util.Arrays;

import java.util.Scanner;

public class Main {

static final int maxn = 1000;

int n; //Number of array elements

int[] a; // array

boolean[] used; // Auxiliary variable, used to mark whether the element has been used during the recursive process, used[i] indicates whether the i-th element has been used

int[] cur; //Save the current arrangement number

// Recursively print the entire arrangement without duplication, currently printing to the idx position

void print_comb(int idx) {

If idx == n, it means that the last element has been traversed and cur can be output.

for(int i = 0; i

if(i > 0) System.out.print(" ");

System.out.print(cur[i]);

}

System.out.println();

}

int last = -1; // In order to avoid duplication, use the last variable to record the value of the last search

for(int i = 0; i

if(used[i]) continue;

if(last == -1 || a[i] != last) { // Only when the current number does not repeat and has not been used, the recursion will continue

last = a[i];

cur[idx] = a[i];

// Backtracking method

used[i] = true;

print_comb(idx 1);

used[i] = false;

}

}

}

public void go() throws FileNotFoundException { // Implement method body }

{

Scanner in = new Scanner(new File("data.in")); The syntax is to create a Scanner object named in, which is used to read input from the file named data.in.

//Read data and sort

n = in.nextInt();

a = new int[n];

for (int i = 0; i

Arrays.sort(a);

//Initialize auxiliary variables and start full arrangement without duplication

cur = new int[n];

used = new boolean[n];

for(int i = 0; i

print_comb(0);

in.close();

}

public static void main(String[] args) throws FileNotFoundException { This is the main method in a Java program, used to start the program entry. In this method, we can perform some operations, such as reading files, processing data, etc. Among them, throws FileNotFoundException indicates that a file not found exception may occur during execution. If this exception occurs, the program will throw a FileNotFoundException exception. In this method, you can write specific code logic to handle file reading and exception handling.

new Main().go();

}

}Objectively speaking, non-recursive and non-repeating full permutations are relatively simple and efficient.

What is the role of recursion in java? Why use recursion

Your two questions are actually one question, right?

The role of recursion: Recursive algorithms can solve some problems defined by recursion.

First of all, we need to understand what is the problem of recursive definition. Simply put, a recursively defined problem is a large problem that contains smaller problems with the same structure but smaller size.

For example, the definition of n factorial can be understood as:

n!= n*(n-1)!

It is not difficult to conclude from the above analysis that (n-1)! is a smaller problem than n!. By continuously decomposing the problem according to this method, we can get some basic known data. Then, through reverse derivation, we can get the final result.

The factorial algorithm of

n is as follows:

private static int jieCheng(int n) { This is a method of calculating factorial, where the parameter n represents the value to be calculated. The following is a detailed explanation: - "private" means that the method is only visible in the current class and cannot be accessed by other classes. - "static" means that the method is a static method and can be called directly through the class name without instantiating the object. - "int" means that the method returns an integer value as the result. - "jieCheng" is the name of the method, which can be named as needed.

if(n == 1)

return 1;

else {

return n*jieCheng(n-1);

}

}

In addition, the definition of binary trees is also recursive, which means that many binary tree operations are implemented through recursion.

Using recursion will make the program quite concise.

Recursive application in java! f20 1 f21 4 fn 2 2 fn 1 fnwhere

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

publicclassTest {

publicstaticintf(intn){

if(n==20){

return1;

}elseif(n==21){

return4;

}elseif(n

returnf(n 2)-2*f(n 1);

}else{

return2*f(n-1) f(n-2);

}

}

public static void main(String[] args) {

System.out.println(f(10)); //Print the value of f(10)

}

}

It has been tested. Enter f(n) in the main function, where n is a manually adjusted parameter, and the corresponding output result can be obtained.

The above is the detailed content of I would like to ask everyone for a detailed explanation of the recursive algorithm in java.. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:Excel办公网. If there is any infringement, please contact admin@php.cn delete
Which Is the Best VPN for ChatGPT? - MiniToolWhich Is the Best VPN for ChatGPT? - MiniToolApr 29, 2025 am 12:50 AM

If you want to use ChatGPT via VPN in an unsupported country, region, or territory, do you know which is the best VPN for ChatGPT? In this post, php.cn Software will introduce some good choices for you. You can select one according to your requiremen

XboxPcAppFT.exe Bad Image Error: Here Is How to Fix It!XboxPcAppFT.exe Bad Image Error: Here Is How to Fix It!Apr 29, 2025 am 12:49 AM

How to fix the “XboxPcAppFT.exe bad image” issue on Windows 11/10? This post from php.cn presents multiple methods to resolve the annoying issue. Please go on with your reading.

How to Fix OneDrive Files Cannot Be Deleted Windows 10/11 - MiniToolHow to Fix OneDrive Files Cannot Be Deleted Windows 10/11 - MiniToolApr 29, 2025 am 12:48 AM

What should do when you want to delete a file or folder in OneDrive, but find that OneDrive files or folders cannot be deleted? Now you can read this post from php.cn to get the best solutions to fix the “OneDrive files cannot be deleted in Windows 1

Display Connection Might Be Limited: Key Factors & SolutionsDisplay Connection Might Be Limited: Key Factors & SolutionsApr 29, 2025 am 12:47 AM

The error message “display connection might be limited” is an annoying issue when you start the device. In this post from php.cn, you can get detailed information about what causes this problem and how to resolve it quickly.

Windows 11 Build 25115 Is Released to Insiders in the Dev Channel - MiniToolWindows 11 Build 25115 Is Released to Insiders in the Dev Channel - MiniToolApr 29, 2025 am 12:46 AM

Microsoft releases a new build to Insiders in the Dev Channel and it is Windows 11 build 25115. This is a higher build compared to the build released to the Beta Channel. You can follow this php.cn post to learn some related information about it.

How to Clean C Drive in Windows 11/10 Without Losing Data - MiniToolHow to Clean C Drive in Windows 11/10 Without Losing Data - MiniToolApr 29, 2025 am 12:45 AM

How do I free up space on my C drive or how do I clear waste on my C drive? This is the topic that php.cn focuses on here. If your C drive is full of old apps and unnecessary programs, you can choose to clean up it. Let’s get started.

ChatGPT 4 vs. ChatGPT 3: the Difference between Them - MiniToolChatGPT 4 vs. ChatGPT 3: the Difference between Them - MiniToolApr 29, 2025 am 12:44 AM

ChatGPT has been updated with GPT-4. To help you better understand this update, we will introduce the differences between ChatGPT 4 and ChatGPT 3. In addition, if you want to recover deleted files on Windows, you can try php.cn Power Data Recovery.

Media Feature Pack Windows 11 Download & Install: Power TacticsMedia Feature Pack Windows 11 Download & Install: Power TacticsApr 29, 2025 am 12:43 AM

How can you download and install Media Feature Pack if you are using Windows 11 N or KN editions?  In this post, php.cn offers a step-by-step guide on getting Windows 11 Media Feature Pack. Let’s look through some details.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools