How to output all combinations of strings and output string combinations

Source: Internet
Author: User

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;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.