CareerCup-BASE CASE AND BUILD

本文介绍了一种打印字符串所有可能排列的算法实现,并提供了一个C++示例程序。该算法通过递归方式逐步增加字符来生成所有可能的排列组合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这个题刷起来感觉比编程之美什么的easy多了

Description: 

Solve the algorithm first for a base case (e g , just one element) Then, try to solve it for elements one and two, assuming that you have the answer for element one Then, try to solve it for elements one, two and three, assuming that you have the answer to elements one and two 

Example: 

Design an algorithm to print all permutations of a string For simplicity, assume all characters are unique.

Testing String: abcdefg

Case “a” --> {a}
Case “ab” --> {ab, ba}
Case “abc” --> ?

#include <iostream>
using namespace std;

void print(char* prefix, char* data, int index, int length)
{
     if(index >= length)
     {
         static int count = 0;
         printf("%d: %s\n", count++, prefix);
         return;
     }
     int prelength = strlen(prefix);
     for(int i=0; i<prelength+1; i++)
     {
         char* s = new char[prelength + 2];;
         int count = 0, j;
         for(j=0; j<prelength+1; j++)
         {
             if(j == i)
                 s[j] = data[index];
             else
                 s[j] = prefix[count++];
         }
         s[j] = '\0';
         print(s, data, index+1, length);
     }
};

int main()
{
    char* data = "abcd";
    print("", data, 0, strlen(data));
    system("pause"); 
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值