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/