Arrangement and combination Summary

Source: Internet
Author: User
Combination 1. bitwise operation implementation and combination: here we introduce the binary conversion method, that is, to map each combination with a binary number, and enumerate each combination while enumerating the binary. For example, if the string is ABCDE
00000 --------- null
00001 ---------
00010 -------- B
00011 --------- AB
00100 --------- C
... ...

11111 -------- ABCDE


The program is shown as follows:
# Include <stdio. h> # include <string. h> void printcombination (char * STR, int I); void combination (char * Str) {int Len = strlen (STR); // Total (1 <Len) no external for (INT I = 0; I <(1 <Len); ++ I) {printcombination (STR, I ); printf ("\ n") ;}} void printcombination (char * STR, int I) {int Len = strlen (STR); For (Int J = 0; j <Len; ++ J) {// check which bits in S are int S = I & (1 <j); If (s) printf ("% C ", STR [J]) ;}} int main () {char STR [] = "ABC"; combination (STR );}


2. Recursive Solution
# Include <stdio. h> # include <string. h> void printcombination (char * STR, int Len, int M, int * arr, const int m); void combination (char * Str) {int Len = strlen (STR ); int * arr = new int [Len]; for (INT I = 1; I <= Len; ++ I) {printcombination (STR, Len, I, arr, i);} Delete [] arr ;} // select the number of M from N for combination /****************************** * *******. first, select the maximum number of N numbers, and then select the number of m-1 in n-1-1 numbers until the number of N-(m-1) numbers is selected. B. Select a smaller number from N to continue the step until the maximum number of available numbers is M. **************************************** **/Void printcombination (char * STR, int Len, int M, int * arr, const int m) {for (INT I = Len; I> = m; -- I) {// select the maximum number in sequence, the next big number .... arr [M-1] = I-1; If (M> 1) {// The number of selection is greater than the number of, from the remaining number of I-1, the combination of the number of m-1 printcombination (STR, I-1 m-1, arr, m);} else {// print M numbers for (Int J = M-1; j> = 0; -- j) {printf ("% C ", STR [arr [J]);} printf ("\ n") ;}} int main () {char STR [] = "ABCD"; combination (STR ); return 0 ;}



3. Non-Recursive Implementation first, initialize an array of n elements (all composed of 0, 1), initialize the first M elements to 1, followed by 0. At this time, the first combination can be output. The number of subscripts corresponding to the element of 1.
Algorithm start: Search for the first 10 combinations, convert them to 01, and then push all the first 1 to the left, that is, ensure that the first 1 is at the leftmost. Then you can output a combined result according to the 01 sequence.
If no 10 combinations are found, it means all the situations are output. Why? You think (n = 5, M = 3 as an example) The first is 11100, the last is 00111, and there is no combination of 10.
This idea of converting the problem to the 01 series (that is, the true and false series) is worth consideration and reference.
For example, find the combination of 3 in five:
1 1 1 0 0 // 1, 2, 3
1 1 0 1 0 // 1, 2, 4
1 0 1 1 0 // 1, 3, 4
0 1 1 1 0 // 2, 3, 4
1 1 0 0 1 // 1, 2, 5
1 0 1 0 1 // 1, 3, 5
0 1 1 0 1 // 2, 3, 5
1 0 0 1 1 // 1, 4, 5
0 1 0 1 1 // 2, 4, 5
0 0 1 1 1 // 3, 4, 5

The implementation code is as follows:

#include <stdio.h>   #include <stdlib.h>   #include <string.h>      int l=0;   //function definition   void composition(const char [],int,int);    void printCompostion(const char[],const bool[],int);     //function implementation   void printCompostion(const char source[],const bool comp[],int n){   int i;       for (i=0;i<n;i++)    if (comp[i]==true) printf ("%c-",source[i]);       printf ("\n");      }      void compostion(const char* source,int n,int m){              bool * comp = (bool*)malloc(n*sizeof(bool));          int i;   for (i=0;i<m;i++) comp[i]=true;       for (i=m;i<n;i++) comp[i]=false;          printCompostion(source,comp,n);       l++;          while(true){              for (i=0;i<n-1;i++)                if (comp[i]==true&&comp[i+1]==false) break;              if (i==n-1) return;  //all the compostion is found out                      comp[i]=false;           comp[i+1]=true;              int p=0;   while (p<i){               while (comp[p]==true) p++;   while (comp[i]==false) i--;   if (p<i) {   comp[p]=true;   comp[i]=false;               }   }           printCompostion(source,comp,n);          l++;       }   }       //test function   void testCompostion(){   char* testcase = "abcdefghijklmno";   int n=strlen(testcase);       int m=7;   compostion(testcase,n,m);   }      //main function   void main(){   testCompostion();   printf ("total=%d\n",l);   }   


Full arrangement: 1. Recursive divide-and-conquer algorithm: This algorithm utilizes the divide-and-conquer idea. We start with two numbers, for example, 4 and 5. They have only two 45 and 54 in the full arrangement. If you add 3 to the front, the full arrangement is 345,354, that is, 3 (54). brackets indicate the full arrangement of numbers. Of course there are still 4 (35), 5 (34)... here, you should have seen some points. The full arrangement of three numbers can be divided into three computations. The first calculation is the full arrangement of 3 and (45), and the second calculation is the full arrangement of 4 and (35 ..... that is to say, replace the first element of the sequence with it and each element after it to get three sequences, and then fully arrange the subsequences except the first element. The idea is actually quite simple:
The code is implemented as follows:
#include <stdio.h>   #include <string.h>   #include <stdlib.h>      #define LENGTH 27      int n=0;      void permute(int[],int,int);   void swapint(int &a,int &b);   void printIntArray (int[],int);   //Function Implementation      void swapint(int &a,int &b){   int temp;       temp = a;       a = b;       b = temp;   }      void printIntArray(int target[],int length){       int i;       for (i=0;i<length;i++) printf ("%d",target[i]);       printf ("\n");   }      void permute(int target[],int begin,int end){              if (begin==end) {           printIntArray(target,end+1);           n++;           return;       }       int i;       for (i=begin;i<=end;i++){                  swapint(target[begin],target[i]);           permute(target,begin+1,end);           swapint(target[begin],target[i]);                 }   }      //test Functions   void testPermute(){       int len;       scanf ("%d",&len);              int *testcase =(int *)malloc(len*sizeof(int));              int i;       for (i=0;i<len;i++) testcase[i]=i+1;       permute(testcase,0,len-1);      }      //Main Function   void main(){       testPermute();       printf ("n=%d",n);   }  


2. the efficiency of recursion sometimes forces us to consider other implementations. It is difficult to convert recursive algorithms into non-recursive algorithms, at this time, we should not forget the algorithms implemented by the standard template library, which makes it very easy. STL has a function next_permutation (). Its function is to return true and generate this arrangement if a sequence is sorted by dictionary in the next order, otherwise, false is returned. Note: In order to generate a full arrangement, this sequence is ordered, that is, to call sort once.
Use STL directly
# Include "iostream" # include "algorithm" using namespace STD; void permutation (char * STR, int length) {sort (STR, STR + length ); // do {for (INT I = 0; I <length; I ++) cout <STR [I]; cout <Endl;} must be sorted first ;} while (next_permutation (STR, STR + length);} int main (void) {char STR [] = "ACB "; cout <STR <"the result of all full sorting is:" <Endl; permutation (STR, 3); System ("pause"); Return 0 ;}

The implementation of next_permutation () is as follows:

Template <class bidirectionliterator> bool next_permutation (bidirealialiterator Firt, bidirealialiterator last) {If (first = last) return false; // null interval bidirealialiterator I = first; ++ I; if (I = last) return false; // only one element I = last; // I points to the end -- I; for (;) {bidrectionaliterator II = I; -- I; // above, lock a group of (two) adjacent elements if (* I <* II) // if the first element is smaller than the last element {bidrectionaliterator J = last; // Point J to the end while (! (* I <* -- J); // locate it from the end until it encounters an iter_swap (I, j) element larger than * I; // exchange I, jreverse (II, last); // reverse all elements after II return true;} if (I = first) // returns {reverse (first, last); // All reverse reset return false ;}}}

Self-designed function next_permutation ():
# Include <stdio. h> # include <algorithm> # include <string. h> using namespace STD; // reverse the array void reverse (char * STR, int first, int last) {If (STR = NULL | * STR = '\ 0') return; while (first <last) {char CH = STR [first]; STR [first] = STR [last]; STR [last] = CH; first ++; last -- ;}// print the array void printfstring (char * Str) {for (INT I = 0; I <strlen (STR); ++ I) {printf ("% C", STR [I]);} printf ("\ n");} // find the next array bool next_permutation (char * Str) {If (STR = NULL | * STR = '\ 0 ') return false; int Len = strlen (STR); int I = len-2; int II = I + 1; Int J = len-1; // start from the backend and find the number of the first STR [I] <STR [J] While (STR [I]> STR [II]) {-- I; -- II; // If I <0, it indicates that all rows are arranged if (I <0) {// All reverse (STR, I + 1, len-1); Return false ;}} // find the first digit after STR [I] While (STR [J] <STR [I]) {-- J ;} // exchange char CH = STR [I]; STR [I] = STR [J]; STR [J] = CH; // array reverse (STR, II, len-1); Return true;} int main () {char STR [] = "cab"; int Len = strlen (STR); // The sort (STR, STR + Len); printfstring (STR); // print the full arrangement while (next_permutation (STR) {printfstring (STR) ;}return 0 ;}

See:

Http://blog.csdn.net/hackbuteer1/article/details/7462447

Http://xiaomage.blog.51cto.com/293990/74094

Http://blog.csdn.net/hackbuteer1/article/details/6657435

Arrangement and combination Summary

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.