admin 管理员组

文章数量: 887021

输入字符串“abc“,输出组合a,b,c,ab,ac,bc,abc

输入字符串"abc",输出组合a,b,c,ab,ac,bc,abc

class Main {public static void main(String[] args){String s = new Scanner(System.in).next();combine(s);}public static void combine(String str){char[] in=str.toCharArray();StringBuilder out = new StringBuilder();List<String> list = new ArrayList<>();//将组合添加至list中,排序。按照a,b,c,ab,ac,abc输出allCombine(in,out,0,list);list.stream().forEach(s -> System.out.print(s+" "));}public static void allCombine(char[] ch, StringBuilder sb, int start, List<String> list){int len=ch.length-1;for(int i=start;i<=len;i++){sb.append(ch[i]);//System.out.print(sb+" "); =>不添加至list中,直接打印 a,ab,abc,abcd,ac,acd,b,bc,bd,dlist.add(sb+"");Collections.sort(list,(o1, o2) -> o1.length() - o2.length());if(i<len){allCombine(ch,sb,i+1,list);}sb.setLength(sb.length()-1);//执行完abcd后,回溯 -> abc -> ab重新执行 abd}}
}

本文标签: 输入字符串“abc“,输出组合a b c AB Ac