輸入一個字符串,打印出該字符串中字符的所有排列。

/*
copyright@nciaebupt 轉載請註明出處
題目:輸入一個字符串,打印出該字符串中字符的所有排列。例如輸入字符串abc,則輸出由字符a、b、c所能排列出來的所有字符串abc、acb、bac、bca、cab和cba。
分析:這是個遞歸求解的問題。遞歸算法有四個特性:(1)必須有可達到的終止條件,否則程序將陷入死循環;(2)子問題在規模上比原問題小;(3)子問題可通過再次遞歸調用求解;(4)子問題的解應能組合成整個問題的解。
對於字符串的排列問題。如果能生成
n-1個元素的全排列,就能生成n個元素的全排列。對於只有1個元素的集合,可以直接生成全排列。全排列的遞歸終止條件很明確,只有1個元素時。
*/
#include <cstdlib>
#include <cstring>
#include <iostream>

void exchange(char * str, int i, int j){
  if(str == NULL){
    return;
  }
  char tmp = str[i];
  str[i] = str[j];
  str[j] = tmp;
}

void fullPermutationsOfString(char * str, int begin, int end){
  if(str == NULL || begin > end){
    return ;
  }
  if(begin == end -1){
    std::cout<<str<<std::endl;
  }
  else{
    for(int i = begin; i < end; ++i){
      exchange(str, begin, i);
      fullPermutationsOfString(str, begin+1, end);
      exchange(str, begin, i);
    }
  }
}

int main(int argc, char ** argv){
  char str[] = "abc";
  int len = strlen(str);

  std::cout<<len<<std::endl;
  fullPermutationsOfString(str, 0, len);

  system("pause");
  return 0;
}



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