Blue Bridge Cup algorithm tutorial: full permutation problem

Topic information

把 1∼n 这 n 个整数排成一行后随机打乱顺序,输出所有可能的次序

input format

一个整数 n

output format

按照从小到大的顺序输出所有方案,每行 1 个。

首先,同一行相邻两个数用一个空格隔开。

其次,对于两个不同的行,对应下标的数一一比较,字典序较小的排在前面

Input sample:

3

Sample output:

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

ideas

The full permutation problem is very similar to recursive implementation of exponential enumeration, and it is also a recursive problem.
To learn about recursive implementation of exponential enumerations, refer to the article link here .

It's just that the full permutation problem is regardless of the order, and each number must be printed out. We can draw a recursive search tree to represent the search process. In order not to repeat the answer, we adopt a recursive strategy of enumerating where each number is placed in turn. The picture is as follows.

insert image description here

code

import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.

 * @Description: 全排列
 */
public class Main {
    
    
    static  int N=15;
    //定义一个Boolean类型的st数组表示状态,代表当前这个数有没有被用过了。
    static  boolean st[]=new boolean[N];
    static  int n=0;
    //记录已经走过的方案
    static  int path[]=new int[N];
    static  void dfs(int u){
    
    
        //如果u>n了,说明已经递归完了一种方案了,输出这个方案
        if(u>n){
    
    
            for (int i =1 ; i <=n  ; i++) {
    
    
                System.out.print (path[i]+" ");
            }
            //输出一种后打印换行,return结束
            System.out.println ();
            return;
        }
        //对于1-n枚举每一个数
        for (int i = 1 ; i <=n  ; i++) {
    
    
            //如果i还没有走过,就进入if的判断
           if(st[i]==false){
    
    
               //先将i的状态标记成true。表示走过了
               st[i]=true;
               //记录这时候的path
               path[u]=i;
               //递归到下一层
               dfs (u+1);
               //回溯,将上次修改的改回来
               st[i]=false;
           }
        }
    }
    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/122588298