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

Source: Internet
Author: User

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

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.