1 回答

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超4個(gè)贊
這是我能想到的最簡單的方法
String str= "abc";
ArrayList<String> letters = new ArrayList<String>();
HashSet<String> combinations = new HashSet<String>();
for(int i = 0; i<str.length();i++) {
//Break String into letters
letters.add(str.substring(i,i+1));
}
for(int i = (str.length()*2)+1;i>0;i--) {
//Will loop through maximum possible outcomes
String result = "";
String bin = Integer.toBinaryString(i);
//System.out.println(bin);
while(bin.length()<3) {
bin="0"+bin;
}
for(int b = bin.length();b>0;b--) {
if(bin.substring(b-1,b).equals("1"))result = result.concat(letters.get(b-1));
}
for(int b = bin.length();b>0;b--) {
if(bin.substring(b-1,b).equals("0"))result = result.concat(letters.get(b-1));
}
combinations.add(result);
}
System.out.println(str);
for(String c : combinations) {
System.out.println(c);
}
它使用二進(jìn)制循環(huán)遍歷原始字符串的數(shù)組,然后將結(jié)果添加到哈希集以刪除重復(fù)項(xiàng)
添加回答
舉報(bào)