【算法】C++打印字符串的全排列

剑指offer38   打印字符串的全排列

 

我的方法

// sort algorithm example
#include <iostream >     // std::cout
#include <algorithm>    // std::sort
#include <vector>       // std::vector
#include <map>
#include <assert.h>
#include <stack>
#include <queue>
#include <unordered_map>


using namespace std;
void print_str(char str[], map<int,char> placed,int index,int length)
{
    
    int count = 0;
  //按顺序在剩下的空位用for进行选择自己的位置
    for (int count0 = 0; count0 < length-index && count<length; )
    {
        
        if (placed[count])
        {
            count++;
            continue;
        }
        else
        {
            placed[count] = str[index];
            print_str(str, placed, index + 1, length);

       //删除最后加进去的元素
auto it
= placed.find(count); placed.erase(it); count0++; count++; } } if (index == length) { for (int i = 0; i < length; i++) { cout << placed[i]; } cout << "\n"; return; } } void solve(char str[],int length) { if (!str) cout << "illegal input!!";

map<int, char> placed; print_str(str, placed,0, length-1); } void test1() { char test1[] = "abcd"; int length= sizeof(test1); solve(test1,length); } int main() { test1(); }

 

答案

#include <cstdio>

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

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

    Permutation(pStr, pStr);
}

void Permutation(char* pStr, char* pBegin)
{
    if(*pBegin == '\0')
    {
        printf("%s\n", pStr);
    }
    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 Test(char* pStr)
{
    if(pStr == nullptr)
        printf("Test for nullptr begins:\n");
    else
        printf("Test for %s begins:\n", pStr);

    Permutation(pStr);

    printf("\n");
}

int main(int argc, char* argv[])
{
    Test(nullptr);

    char string1[] = "";
    Test(string1);

    char string2[] = "a";
    Test(string2);

    char string3[] = "ab";
    Test(string3);

    char string4[] = "abc";
    Test(string4);

    return 0;
}

 

posted @ 2020-12-09 20:14  nntzhc  阅读(685)  评论(0)    收藏  举报