All in one (java)

Full arrangement: taking m (m≤n) elements from n different elements and arranging them in a certain order is called an arrangement of taking m elements from n different elements. When m = n, all permutations are called full permutations.

For example: {1, 2, 3} The full arrangement is: {1, 2, 3}, {1, 3., 2}, {2, 1, 3}, {2, 3, 1}, {3, 1, 2}, {3, 2, 1}.

Thinking analysis: We can analyze the results gradually from small to large. If there is only one element, the result of the full arrangement is itself (recursive exit); if there are two elements, it is equivalent to inserting new elements in front of and behind it on the basis of the previous layer; if there are three elements, it is equivalent to New elements are inserted in front of, behind, and in the middle on the basis of one layer. You can use recursion to write.

code show as below:

import java.util.ArrayList;
import java.util.Scanner;
public class Qpl {
    //全排列递归求解(即对新元素进行插入)
    static ArrayList<String> ql(String a,int n)
    {
        ArrayList<String> news=new ArrayList<>();//新建一个集合
        if(n==0||n<0)//递归出口
        {
            news.add(a.substring(0,1));//如果只剩一个元素,则直接加入到list中
            return news;
        }
        ArrayList<String> old=ql(a,n-1);//递归求解出n-1层list
        for (String temp:old)//在其最前面和最后面插入
        {
            StringBuilder jj1=new StringBuilder();
            jj1.append(a.substring(n,n+1)+temp);
            String ss1=jj1.toString();
            news.add(ss1);
            StringBuilder jj2=new StringBuilder();
            jj2.append(temp+a.substring(n,n+1));
            String ss2=jj2.toString();
            news.add(ss2);
        }
        for (String temp:old)//插入元素中间
        {
           for (int i=1;i<=temp.length()-1;i++)
           {
               StringBuilder jj=new StringBuilder();
               jj.append(temp.substring(0,i)+a.substring(n,n+1)+temp.substring(i));
               String ss=jj.toString();
               news.add(ss);
           }
        }
        return news;
    }
    public static void main(String[] args) {
        Scanner a=new Scanner(System.in);//字符串输入
        String b=a.nextLine();
        ArrayList<String> arrayList=ql(b,b.length()-1);
        System.out.println(arrayList);
    }
}

The results are as follows:

Insert picture description here

Published 14 original articles · praised 0 · visits 235

Guess you like

Origin blog.csdn.net/lianggege88/article/details/105564883