* NEU_STONE's websit *
  Permutation
 

#include <iostream>
#include
<assert.h>
// using namespace std;

static int g_nCount = 0;

int testMain(void)
{
    
char str[] = "abcefg";
    
     permuteRecursive
(str, 0, strlen(str)-1);

     permuteSTL( str );

     return
0;
}


/* 1. Recursive method */

void permuteRecursive( char* pElems, int mid, int end )
{
    if (mid == end)
    {
       
printf( "%d : %sn", ++ g_nCount, pElems );
        return;
   
}

   
for (int i = mid; i <= end; i++)
    {
       
swap( *(pElems+mid), *(pElems+i) );
        permuteRecursive( pElems, mid + 1, end );
        swap( *(pElems+mid), *(pElems+i) );
    }
}

/* 2. STL method */

#include <string>
#include <algorithm>

int permuteSTL(char* pstr)
{
    std::string s = pstr;
    do
   
{
        std::cout << ++ g_nCount<<
" : " << s << endl;
   
}
   
while ( std::next_permutation( s.begin(), s.end() ) == true );
    
   
return 0;
}

/* 3. Non-Recursive method */

void Reverse(char* pBegin , char* pEnd)
{
    while(pBegin < pEnd) 
    {
        swap(*pBegin++ , *pEnd--); 
    }
}


bool permuteNonRecursive(char* pstr)
{
     assert(pstr); 
     printf("%d : %sn", ++nCountOfPermutation, pstr );

     char *p , *q , *pFind; 
     char *pEnd = pstr + strlen(pstr) - 1; 
     if(pstr == pEnd) 
          return false;

     p = pEnd; 
     while(p != pstr) 
     { 
          q = p; 
          p--; 
          if(*p < *q) 
          { 
               pFind = pEnd; 
               while(*pFind < *p) 
               --pFind; 
               swap(*p , *pFind); 
               Reverse(q , pEnd); 
               return true; 
          } 
     } 
     Reverse(pstr , pEnd); 
     return false;
}

int cmp(const void *a,const void *b)

     return int(*(char *)a - *(char *)b);
}


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

 
  Today, there have been 13 visitors (14 hits) on this page!  
 
This website was created for free with Own-Free-Website.com. Would you also like to have your own website?
Sign up for free