【算法】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 @   nntzhc  阅读(665)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
点击右上角即可分享
微信分享提示