How to output all combinations of strings and output string combinations
Problem description: How to output all combinations of strings if all characters in a string are not repeated. For example, the result of abca is a, B, c, AB, ac, bc, and abc. The easiest thing to think of is recursion, but the efficiency will become very poor, because the stack is called 2 ^ n. To improve efficiency, You can construct a 01 string with a length of n, indicates whether the output result contains a certain character, such as 001-> c, 010-> B, 101-> ac ......, therefore, the original question is to output the 2 ^ n-1 strings corresponding to the "001"-"111" combination.
Public static void main (String [] args ){
String s = "abc ";
ArrayList <String> result = combineString (s );
For (String r: result ){
System. out. println (r );
}
}
Private static ArrayList <String> combineString (String s ){
Int len = s. length ();
ArrayList <String> list = new ArrayList <String> ();
Int count = (int) (Math. pow (2, len ));
For (int I = 1; I <count; ++ I ){
String temp = "";
String str = Integer. toBinaryString (I );
While (str. length () <len ){
Str = "0" + str;
}
For (int j = 0; j <str. length (); ++ j ){
If (str. charAt (j) = '1 '){
Temp + = s. charAt (j );
}
}
List. add (temp );
}
Return list;
}