Returns the character of a set and a positive number k. obtain all the string sets that can contain k and print-all-combinations-of-given-length.

Source: Internet
Author: User

Returns the character of a set and a positive number k. obtain all the string sets that can contain k and print-all-combinations-of-given-length.

// Give a set character and a positive number k, and find all the string sets whose length can be k.

/*

Input:

Set [] = {'A', 'B'}, k = 3

Output:

Aaa

Aab

Aba

Abb

Baa

Bab

Bba

Bbb

Input:

Set [] = {'A', 'B', 'C', 'D'}, k = 1

Output:

A

B

C

D



Package recursion; import java. util. arrayList; public class N_sets_form_length_k_string {// returns a set character and a positive number k. Find all the string sets that can be composed of k by this set/* Input: set [] = {'A', 'B'}, k = 3 Output: aaaaababaabbbaabbbabbbbbinput: set [] = {'A', 'B', 'C ', 'D'}, k = 1 Output: abcd */public static void main (String [] args) {ArrayList <Character> set = new ArrayList <Character> (); set. add ('A'); set. add ('B'); int k = 3; ArrayList <String> al = New ArrayList <String> (); StringBuilder sb = new StringBuilder (); rec (set, k, al, sb); System. out. println (al);} // after the first character is selected, the problem is converted to a recursive problem of the K-1, and each element in the set can act as the first character. // The end condition is when k is 0. Public static void rec (ArrayList <Character> set, int k, ArrayList <String> al, StringBuilder sb) {if (k = 0) {al. add (new String (sb); return ;}for (int I = 0; I <set. size (); I ++) {sb. append (set. get (I); rec (set, K-1, al, sb); sb. deleteCharAt (sb. length ()-1); // use StringBuilder to delete the last character }}}

Http://www.geeksforgeeks.org/print-all-combinations-of-given-length/

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.