Java求一個字符串的全部排列,首創思路(不用遞歸,不用三層循環)

求一個字符串的全部排列,網上找到的全部方法要麼是遞歸,要麼是三層for循環。 java

 

我這個方法不須要遞歸,只要兩層for循環,思路很是獨特。缺點是字符串長度較長時執行時間可能要幾萬年。但畢竟是本身的原創思路,且網上沒有這個算法,姑且記錄下來。算法

 

 

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

public class Main {

	private List<String> elements = new ArrayList<>();
	private int length;

	public Main(String input) {
		length = input.length();
		for (int i = 0; i < length; i++) {
			elements.add("");
		}
		for (int i = 0; i < length; i++) {
			String element = input.substring(i, i + 1);
			elements.set(i, element);
		}
	}

	private List<String> permutate() {
		List<String> permutations = new ArrayList<>();
		
		for (int p = 0; p < Short.MAX_VALUE; p++) { // 字符串較長時須要改爲一個很大的數
			StringBuilder randomSb = new StringBuilder();
			for (int i = 0; i < length; i++) {
				int r = new Random().nextInt(length);
				if (!randomSb.toString().contains(elements.get(r))) {
					randomSb.append(elements.get(r));
				}
			}
			if (!permutations.contains(randomSb.toString()) && randomSb.toString().length() == length) {
				permutations.add(randomSb.toString());
			} 
		}
		return permutations;
	}

	public static void main(String[] args) {
		Main main = new Main("ABCDE");
		List<String> result = main.permutate();

		for (String s : result) {
			System.out.println(s);
		}
		
		System.out.println("Number of permutations is " + result.size());

	}

}

 

執行結果:json

BEDCA
EBADC
ADBCE
DCEBA
ECDAB
DEACB
DACEB
CBDAE
EDACB
DEBCA
ACBDE
ABCDE
EABDC
CDAEB
DCBAE
ACDEB
BACED
DECBA
DECAB
CEDAB
DBECA
CEDBA
DAEBC
DCAEB
AEBDC
ADCBE
CDEAB
EDBCA
AEBCD
BECDA
CBEDA
BACDE
CEBDA
BADCE
BDCEA
DCABE
BDAEC
BEACD
BCEDA
DBCAE
DABEC
BCDAE
BCEAD
CEABD
BADEC
EBACD
CEADB
ACEBD
CADBE
BECAD
EADBC
ADBEC
ACBED
EBCAD
DABCE
EACDB
EABCD
ABECD
AECBD
ECDBA
BDEAC
DAECB
DBAEC
DBCEA
ABDEC
AECDB
CAEDB
DACBE
EADCB
BDECA
CABDE
CBADE
EDCBA
BEDAC
EDBAC
EBCDA
ADCEB
ECABD
ACDBE
ABEDC
BDACE
BDCAE
ECBDA
BCDEA
EBDAC
CBDEA
ECADB
ECBAD
CADEB
DEABC
BAEDC
CEBAD
BEADC
EDABC
CDBAE
BCAED
AEDBC
DCEAB
CDEBA
ADECB
DEBAC
DCBEA
AEDCB
DBEAC
CDABE
BCADE
CAEBD
ACEDB
CBAED
EACBD
ADEBC
EBDCA
CBEAD
CABED
ABDCE
BAECD
DBACE
ABCED
EDCAB
CDBEA
Number of permutations is 120
相關文章
相關標籤/搜索