A Java recursive implementation of string array element permutation and composition

Source: Internet
Author: User

Java recursive implementation of permutations and combinations (reference)

We often encounter questions about permutations and combinations in the course of a written interview, but these can be achieved by recursive simplicity, as shown in the following two examples:

(1) questions about string arrangement

Enter a string that prints out all the permutations of the characters in the string. For example, the input string abc, the output of the characters A, B, C can be arranged out of all the strings of ABC, ACB, BAC, BCA, Cab and CBA.

Think of it this way: fix the first character a, and then the two-character BC arrangement. When the two-character BC arrangement is made, we swap the first character A with the second B to get the BAC, and then we fix the first character B and then the two-character AC arrangement. Now it's time to put C in the first place. Remember that we have previously exchanged the first character A and the second B, in order to ensure that this time C is still in the first place with the A exchange, we have C and the first character exchange before the first to Exchange B and a back. After exchanging B and a, take C and a in the first position to exchange, get CBA. We fixed the first character C again, and we asked for the arrangement of the next two characters, B, a. This is written as a recursive procedure as follows:

1  Packagecom.meession.weekWork;2 ImportJava.util.Scanner;3  Public classoutputstringallconbinations {4      Public Static voidPermutatesequence (Char[] Strarrs,inti) {5         Chartemp;6         if(strarrs==NULL|| i>strarrs.length| | I<0){7             return;8         }9         Else if(i==strarrs.length) {Ten System.out.println (strarrs); One         } A         Else{ -              for(intj=i;j<strarrs.length;j++){ -temp = Strarrs[j];//swaps the prefix with the current character theSTRARRS[J] =Strarrs[i]; -Strarrs[i] =temp; -Permutatesequence (Strarrs, i+1); -temp =Strarrs[j]; +STRARRS[J] =Strarrs[i]; -Strarrs[i] =temp; +             } A         } at     } -      Public Static voidMain (string[] args) { -Scanner in =NewScanner (system.in); -String str =in.nextline (); -         CharStrarrs[] =Str.tochararray (); -Permutatesequence (Strarrs, 0); in     } -}

(2) questions about the composition

Enter a string that prints all the combinations of characters in the string. For example, if you enter ABC, its combination is a, B, C, AB, AC, BC, ABC.

Suppose we want to find a combination of M characters in a string of length n. We first scan the first character of a string. For the first character, we have two options: one is to put this character in the combination, and then we need to select the m-1 character in the remaining n-1 characters, and the second is not to put the character in the combination, next we need to select the remaining n-1 characters m character. Both of these options are easy to implement recursively.

1 Importjava.util.ArrayList; 2 Importjava.util.List; 3 ImportJava.util.Queue; 4  Public classCombination {5      Public Static voidCombiantion (Charchs[]) {  6         if(chs==NULL|| Chs.length==0){  7             return ; 8         }  9List<character> list=NewArrayList (); Ten          for(inti=1;i<=chs.length;i++){   OneCombine (chs,0, i,list);  A         }   -     }   -     //starting from the beginning of the character array, select the number of characters to join the list the      Public Static voidCombineChar[]cs,intBeginintNumber,list<character>list) {   -         if(number==0){   - System.out.println (list.tostring ());  -             return ;  +         }   -         if(begin==cs.length) {   +             return;  A         }   at List.add (Cs[begin]);  -Combine (cs,begin+1,number-1, list);  - List.remove ((Character) cs[begin]);  -Combine (cs,begin+1, number,list);  -     }   -      Public Static voidMain (String args[]) { in         CharChs[]={' A ', ' B ', ' C '};  - combiantion (CHS);  to     }   +}

A Java recursive implementation of string array element permutation and composition

Related Article

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.