1. 程式人生 > >劍指offer(面試題38):字串的排列

劍指offer(面試題38):字串的排列

  • 分析:

    求字串中所有字元的全排列,實際上按照全排列的計算公式來理解,第一步是求出所有可能出現在第一個位置的字元,即用首個字元分別後餘下的字元交換;第二步是固定首個字元,餘下字元組成的子串進行第一步的計算。實際上這就是一個遞迴的過程。

/*
* 輸入一個字串,列印字串中的字元組成的全部組成序列(全排列) 
*/
#include<iostream>
#include<string>
using namespace std;

/*
* @param count 當前列印的第count個序列
* @param str 原序列的引用
* @param pBegin 當前被計算字元(子)串的首個字元的下標
*/
void permutaion(string& str, int pBegin, int& count) { if(pBegin == str.size()) { cout << count << ": " << str << endl; ++count; } else { for(int i = pBegin; i < str.size(); i++) { //交換pBegin和str[i] char
tmp = str[pBegin]; str[pBegin] = str[i]; str[i] = tmp; // 遞迴計算,pBegin的下一個字元為下一輪的首字元 permutaion(str, pBegin+1, count); // 將pBegin換回當前的原位置,繼續以str[pBegin]為首的迴圈 tmp = str[pBegin]; str[pBegin] = str[i]; str[i] = tmp; } } } void
permutation(string& str) { if(str.size() == 0) return; int pBegin = 0, count = 1; permutaion(str, pBegin, count); } int main() { string str = "abcd"; permutation(str); }