Full arrangement idea 2:
If {a, b, c} 's full arrangement result is {a, b, c}, {a, c, b} {b, a, c} {b, c, a} {c, b, a} {c, a, b}. It can be seen that we change the first bit of the character array in turn, and the remaining two bits can be solved recursively, but each time a situation is solved, it will disrupt its original order, so we need to go back and return to its original Some states.
code show as below:
import java.util.ArrayList;
import java.util.Scanner;
public class Qpal {
//全排列法二(多支路递归回溯)
ArrayList<String> news=new ArrayList<>();//需要将Arraylist建立为全局变量
public ArrayList<String> qpl1(String a)
{
char []b=a.toCharArray();//转为字符数组方便各个交换
ArrayList<String> news1=qpl(b,0);
return news1;
}
static void swap(char []a,int b,int c)//交换数组中的两个值
{
char temp=a[c];
a[c]=a[b];
a[b]=temp;
}
private ArrayList<String> qpl(char []a, int b)
{
if(b==a.length)//递归出口
{
news.add(new String(a));
}
for (int i=b;i<=a.length-1;i++)
{
swap(a,b,i);//交换第一位元素
qpl(a,b+1);
swap(a,b,i);//回溯
}
return news;
}
public static void main(String[] args) {
Scanner a=new Scanner(System.in);
String b=a.nextLine();//字符串输入
ArrayList<String> news=new Qpal().qpl1(b);
System.out.println(news);
}
}
The results are as follows: