求一个字符串的所有排列,网上找到的所有方法要么是递归,要么是三层for循环。
我这个方法不需要递归,只要两层for循环,思路非常独特。缺点是字符串长度较长时执行时间可能要几万年。但毕竟是自己的原创思路,且网上没有这个算法,姑且记录下来。
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Main {
private List 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 permutate() {
List 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 result = main.permutate();
for (String s : result) {
System.out.println(s);
}
System.out.println("Number of permutations is " + result.size());
}
}
执行结果:
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