筆試面試之字符串的全排列

輸入一個字符串,打印出該字符串中字符的所有排列。例如輸入字符串abc,則輸出由字符abc所能排列出來的所有字符串abcacbbacbcacabcba

 

 

我們以三個字符abc爲例來分析一下求字符串排列的過程。首先我們固定第一個字符a,求後面兩個字符bc的排列。當兩個字符bc的排列求好之後,我們把第一個字符a和後面的b交換,得到bac,接着我們固定第一個字符b,求後面兩個字符ac的排列。現在是把c放到第一位置的時候了。記住前面我們已經把原先的第一個字符a和後面的b做了交換,爲了保證這次c仍然是和原先處在第一位置的a交換,我們在拿c和第一個字符交換之前,先要把ba交換回來。在交換ba之後,再拿c和處在第一位置的a進行交換,得到cba。我們再次固定第一個字符c,求後面兩個字符ba的排列。


既然我們已經知道怎麼求三個字符的排列,那麼固定第一個字符之後求後面兩個字符的排列,就是典型的遞歸思路了。

基於前面的分析,我們可以得到如下的參考代碼:


void Permutation(char* pStr, char* pBegin);

void Permutation(char* pStr)
{
      Permutation(pStr, pStr);
}

/////////////////////////////////////////////////////////////////////////
// Print the permutation of a string,
// Input: pStr   - input string
//        pBegin - points to the begin char of string
//                 which we want to permutate in this recursion
/////////////////////////////////////////////////////////////////////////
void Permutation(char* pStr, char* pBegin)
{
      if(!pStr || !pBegin)
            return;

      // if pBegin points to the end of string,
      // this round of permutation is finished, 
      // print the permuted string
      if(*pBegin == '/0')
      {
            printf("%s/n", pStr);
      }


      // otherwise, permute string
      else
      {
            for(char* pCh = pBegin; *pCh != '/0'; ++ pCh)
            {
                  // swap pCh and pBegin
                  char temp = *pCh;
                  *pCh = *pBegin;
                  *pBegin = temp;

                  Permutation(pStr, pBegin + 1);

                  // restore pCh and pBegin
                  temp = *pCh;
                  *pCh = *pBegin;
                  *pBegin = temp;
            }
      }
}

轉貼自:http://zhedahht.blog.163.com/blog/static/254111742007499363479/

 

發佈了11 篇原創文章 · 獲贊 0 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章