About Recursive Functions

Asked 2 years ago, Updated 2 years ago, 86 views

I don't understand the implementation of this problem, which is answered using a recursive function.
The understanding of the recursive function itself is an understandable state of implementation, such as an overview and a simple Fibonacci sequence.
It may be obvious that you can understand the code if you read it carefully, but I can't imagine the recursive function below.
コード I tried to output a value like debug in the middle of the code.

I apologize for the inconvenience, but I would appreciate it if you could explain it in detail.

Also, any problem of using recursive functions is often difficult to understand.
I would appreciate it if you could let me know if there is anything I can do to understand or implement recursive functions.

▼Example function implementation (java)

 void dfs(intk, intres, intleft) {
        if(res<0)return;
        if(res==0){
            for(inti=0;i<k-1;i++){
                System.out.print(a[i]+"");
            }
            System.out.println(a[k-1]);
            return;
        }
        for(inti=left;i>=1;i--){
            a[k] = i;
            dfs(k+1,res-i,i);
        }
    }

▼Examples of calls

dfs(0,n,n); 

nn is an input value such as 5

▼Problems
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0507

There are n sheets of square paper of the same size. Arrange the bottom of these sheets horizontally in several rows. However, adjacent columns must be arranged so that the left side is not lower than the right side. For example, if n=5, there are seven possible arrangements.

Let's express these as columns of squares arranged in each column. For example, if n = 5, each of them is

 (5)(4,1)(3,2)(3,1,1)(2,2,1)(2,1,1)(2,1,1)(1,1,1)(1,1,1)

be represented as .

When you enter n, create a program that outputs everything in the dictionary order. n と30. However, the dictionary order is a1>b1 or an integer i>1 exists and a1=b1,..., ai-1=bi-1 and ai>bi are the first, b2...

Input data consists of one line with n written on the first line.

The output must be arranged one line at a time in a dictionary order, followed by a new line. The output of (a1, a2, ..., as) must be arranged by dividing the integers a1, a2, ..., as into spaces.

Example Input 1
5
 
Sample Output 1
5
4 1
3 2
3 1 1
2 2 1
2 1 1 1
1 1 1 1 1

Enter
Inputs consist of multiple datasets. When n is 0, the input ends. The number of datasets does not exceed 5.

Output
For each data set, output everything in dictionary order.

Example Input
5
5
0
Sample Output
5
4 1
3 2
3 1 1
2 2 1
2 1 1 1
1 1 1 1 1
5
4 1
3 2
3 1 1
2 2 1
2 1 1 1
1 1 1 1 1

Browse: AIZU ONLINE JUDGE http://judge.u-aizu.ac.jp/onlinejudge/

algorithm

2022-09-30 21:38

3 Answers

The title of the sentence is too long, but in short, it is a task to get a sequence that satisfies "left 」 right".

Recursive is easy to understand if you think about it as follows:

1. In the middle of recursion
·It is in this state now → What should I do next?

2. End Recursive
·Finish when these conditions are met

For a brief illustration of the example presented,

In the middle of recursion:
·The left side of the position you are paying attention to has already been confirmed, so you don't need to consider it
·Put n pieces in the position you are paying attention to → Due to the title, you can put n pieces or less next time, so you can put them down and go one more time to the right by recursing
ending recursive:
·If you can't put it down, don't display it and exit (res<0 is this: the remaining number is not enough)
·Display and exit when placed correctly (res==0 is this: 0 left)
·After placing one, it ends ( for ends)

It was when Oira understood the order of passage of the binary search tree that she was convinced that she had "got it."At that time, I used structure of to implement it.

In the middle of recursion:
·Display left
·Display yourself
·Display right
Recursively, "Display Left" automatically becomes "Display All Left Elements" (the same goes for the right).Due to the nature of the binary search tree, this is the only ascending display.

ending recursive:
·I myself null

I think this passing order display is a good subject for recursion even though it cannot be easily converted into a loop.

If you can understand mathematical induction, you can understand recursive (in the case of induction, it proves "first").


2022-09-30 21:38

I interpreted it as a question asking you to tell me the image of the source code of the answer, so I will write a comment on the source code.
Roughly speaking, it is an image that determines how many pieces to put in the kth place, and then the arrangement after that is a round throw after the k+1st place, and outputs when the rest is exactly zero.

//k —The length of the block column.
//res —Number of blocks remaining
//left —Number of blocks stacked in the previous location (=maximum number of blocks stacked in subsequent locations)
// a[ ] —An array containing the current block arrangement, where a[i] contains the stacked height of the i-th place.

void dfs(intk, intres, intleft) {
        if(res<0)return;// If the number of blocks left is less than 0, nothing can be done, so exit
        if(res==0){// If you have used it up perfectly
            // Output the current arrangement
            for(inti=0;i<k-1;i++){
                System.out.print(a[i]+"");
            }
            System.out.println(a[k-1]); // Do not leave spaces at the end, so separate cases
            return;
        }
        // If there are still blocks left that can be used
        for(inti=left;i>=1;i--) {// To the extent that the height limit is not exceeded
            a[k] = i; // kth load i blocks
            dfs(k+1,res-i,i); // k+1 has res-i blocks left and can be loaded to a height of i or less
        }
    }


2022-09-30 21:38

Is it easy to understand if I write like this?I'm running it on paiza.io.rest means "remaining" and pos means "position".

import java.util.*;

public class Main {

    private inta[]; // How to sort (a1,..., as)

    publicMain(int size){
        a = new int [size+1]; // a0 is dummy; use a1...as
        a[0] = size;
    }

    public void dfs(intrest, intpos) {
        // Displays the current arrangement when the number of squares remaining is zero
        if(rest==0){
            for (inti=1; i<pos-1;i++)
                System.out.print(Integer.toString(a[i])+"";
            System.out.println (Integer.toString(a[pos-1]));
            return;
        }
        // Otherwise, stack the squares to the current position and move them to the right.
        for(inti=Math.min(rest, a[pos-1]);i>=1;i--){
            a[pos] = i;
            dfs(rest-i, pos+1);
        }
    }

    public static void main(String[]args) arrows Exception {
        // Your code here!

        (new Main(5)).dfs(5,1);
    }
}


2022-09-30 21:38

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.