The number of combinations of input random permutation string of characters, find it and all permutations

problem analysis

This problem can be solved using a recursive algorithm.

First, look at Figure:

ABC given string contains three characters, starting from the first character A, A and B respectively in the second switching position, with A and C exchange on the third position can be obtained by three different The results: ABC, BAC, CBA.

then:

Exchanged for ABC, fixed A, the remaining BC, two different results may be obtained: ABC, ACB

For the BAC, the fixed B, the remaining AC exchange, two different results may be obtained: BAC, BCA

For exchange CBA, fixed C, the rest of the BA, two different results may be obtained: CBA, CAB

So far, ABC got all the results of the whole arrangement.


 

 Specific code as follows:

package test;

import java.util.ArrayList;
import java.util.List;

public class Test1 {
	
	private static List list = new ArrayList<String>();

	public static void main(String[] args) {
		String str = "ABCD";
		int n = str.length();
		Test1 test = new Test1();
		test.per(str, 0, n-1);
		System.out.println(list.size());
	}
	
	private String pro(String str,int i,int j) {
		char temp;
		char[] chars = str.toCharArray();
		temp = chars[i];
		chars[i] = chars[j];
		chars[j] = temp;
		return String.valueOf(chars);
	}
	
	private void per(String str,int a,int b) {
		if(a == b) {
			System.out.println(str);
			list.add(str);
		}else {
			for(int i = a;i <= b;i++){
				str = pro(str,a,i);
				per(str,a+1,b);
			}
		}
	}

}

The output is:

ABCD
ABDC
ACBD
ACDB
ADBC
ADCB
BACD
BADC
BCAD
BCDA
BDAC
BDCA
CABD
CADB
CBAD
CBDA
CDAB
CDBA
DABC
DACB
DBAC
DBCA
DCAB
DCBA
24

Specific implementation is: Recursive plus bubble sort.

Published 30 original articles · won praise 28 · views 50000 +

Guess you like

Origin blog.csdn.net/danruoshui315/article/details/104612923