1 回答
TA贡献1828条经验 获得超4个赞
这是我能想到的最简单的方法
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);
}
它使用二进制循环遍历原始字符串的数组,然后将结果添加到哈希集以删除重复项
添加回答
举报