28. 字符串的排列(代码)

  题目:输入一个字符串,打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a、b、c所能排列出来的所有字符串abc、acb、bac、cab和cba。

  思路:分两步。1.先求出所有可能出现在第一个位置的字符,然后用第一个字符和后面所有字符交换。2.固定第一个字符,让第二个字符和它后面所有的字符交换,以此类推。

#include<iostream>
#include<cstdio>
using namespace std;

void Permutation(char* pStr, char* pBegin)
{
    if (*pBegin == '\0')
    {
        cout << pStr << endl;     //只有一个字符时直接输出
    }
    else
    {
        for (char* pCh = pBegin; *pCh != '\0'; pCh++)
        {
            char temp = *pCh;
            *pCh = *pBegin;
            *pBegin = temp;

            Permutation(pStr, pBegin + 1);

            temp = *pCh;
            *pCh = *pBegin;
            *pBegin = temp;
        }
    }
}

void Permutation(char* pStr)
{
    if (pStr == NULL)
    {
        return;
    }

    Permutation(pStr, pStr);
}

int main()
{
    char ch[] = "abc";
    Permutation(ch);
}

猜你喜欢

转载自my.oschina.net/134596/blog/1799211