The idea of full arrangement in java

  • The idea of ​​full arrangement, in fact, full arrangement is a kind of arrangement and combination, such as 1 2 3, so how many possible combinations are there?

    • According to our subjective consciousness, there are naturally six kinds of ①1 2 3 ②1 3 2 ③2 1 3 ④2 3 1 ⑤3 1 2 ⑥3 2 1

    • Next, explain the full arrangement idea in detail

    • package test;
      
      import java.util.*;
      
      public class Main {
      	
      	public static void main(String[] args) {
      		Scanner sc=new Scanner(System.in);
      		int n=sc.nextInt();  //输入n
      		int[] a=new int[n]; //创建数组a
      		for(int i=0;i<n;i++) {
      			a[i]=sc.nextInt(); // 获取数组a的元素
      		}
      		perm(a,0,n-1);
      	}
      	public static void perm(int[] a,int l,int r) { //l为左指针,r为右指针
      		if(l==r) System.out.println(Arrays.toString(a)); 
      		else {
      			for(int i=l;i<=r;i++) {
      				swap(a,i,l);  // 数组a[i]与a[l]作交换
      				perm(a,l+1,r); // 余下数组作全排列,固 左指针加1,即 l+1
      				swap(a,i,l); // 将数组还原防止重复
      			}
      		}
      	}
      	// 简单的作交换处理 ,定义 交换存储器 temp
      	public static void swap(int[] a,int i,int j) {
      		int temp = a[i];  
      		a[i]=a[j];
      		a[j]=temp;
      	}
      }
      
    •  

Guess you like

Origin blog.csdn.net/qq_49174867/article/details/123851761