Given a set character and a positive number k, find out all that does set it can be made up of length k the string collection
/*
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 {//give a set of characters and a positive number k, All this set can make up a string set of length k/* input:set[] = {' A ', ' B '}, k = 3output:aaaaababaabbbaababbbabbbinput:set[] = {' A ', ' B ', ' C ', ' d ' }, K = 1OUTPUT: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);} When the first character is selected, the problem is transformed into a recursive problem of k-1. Each element in the set can act as the first character.The end condition is that K is 0 o'clock. 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 remove the last character}}}
http://www.geeksforgeeks.org/print-all-combinations-of-given-length/
Copyright notice: This article blog original article. Blogs, without consent, may not be reproduced.
Given a set character and a positive number k, find out all that does set it can be composed of length k the string collection Print-all-combinations-of-given-length