Blue Bridge Cup Algorithm Tutorial: Detailed Explanation of Recursive Implementation of Exponential Enumeration Algorithm

foreword

When starting to learn a programming language, the learning of recursion is indispensable. We all know that recursion is the process of a function calling itself. Let's take a look at a recursive advanced application problem.

Topic information

1∼n 这 n 个整数中随机选取任意多个,输出所有可能的选择方案。
输入格式
输入一个整数 n。
输出格式
每行输出一种方案。

同一行内的数必须升序排列,相邻两个数用恰好 1 个空格隔开。

对于没有选任何数的方案,输出空行。
样例1:输入: n=3


输出: 第一行为空,也是答案的一种。

3
2
2 3
1
1 3
1 2
1 2 3

ideas

Let's take a look at the example first. The given value is n=3. For each number, there are two options or no options. The total result is 8. As above.

For every kind of recursion problem, a recursion tree can be drawn. To represent each recursion, all the leaves of the tree are the result of the recursion. Let's simulate a recursive tree with n=3, but this time the problem comes, how can I record all 8 schemes without any leakage? The answer is in order, assuming n=3, then there are 3 A pit, - - -, the first pit can only put 1, or nothing, the same is true for the latter two.
This will include all possible outcomes.

The orange color pointer represents whether the current position is put or not.
insert image description here

code

import java.util.Scanner;

public class Main {
    
    
    static  int N=16;
    //st数组表示当前这个坑的状态,选或者不选。
  static   boolean st[]=new boolean[N];
   static int n=0;
  static   void dfs(int u){
    
    
        //因为从1开始所以u>n的时候才是答案
        if(u>n){
    
    
            for (int i = 1 ; i <=n  ; i++) {
    
    
                    //当st[i]=ture的时候意思是选了,这时候输出i的值
                if(st[i]==true){
    
    
                    System.out.print (i+" ");
                }
            }
            //打印完了换行
            System.out.println ();
            //递归结束
            return;
        }
        
        //下面是两种分支,选,不选、不选是2,选是1,记得递归完了后恢复现场
       st[u]=true;
       //选了之后递归刀下一个坑
        dfs (u+1);
        //递归结束后,回溯上到一层,因为上一曾还没有选,所以要把它修改回false。
        st[u]=false;
        
        //这是不选的情况
        st[u]=false;
        //同样也是递归,但他本来就是false,Boolean数组默认就是false,就可以不用写了。
        dfs (u+1);
       
    }
    public static void main (String[] args) {
    
    
        Scanner s=new Scanner (System.in);
         n=s.nextInt ();
        dfs(1);
    }
}


Guess you like

Origin blog.csdn.net/guankunkunwd/article/details/122587551