gpt4 book ai didi

c++ - 数组中字符的排列

转载 作者:搜寻专家 更新时间:2023-10-31 00:20:15 25 4
gpt4 key购买 nike

我输入一个字符数组,并希望得到该数组的所有可能组合作为输出。例如,如果我输入字符数组 = 'a,b,c',我想以这种形式输出:

a b c,
a c b,
b a c,
b c a,
c a b,
c b a

同样,如果我输入 4 个字符,我想从中得到 24 种组合。我为此编写了一个代码,但它返回的组合仅为输入字符数量的 2 倍。也就是说,如果我输入 3 个字符(没错),代码会返回 6 种组合,但如果我输入 4 个字符,它只会返回 8 种可能的组合,而不是 24 种组合。我的代码如下:

#include <iostream>
#include<string.h>
#include<stdio.h>
using std::cout;
void getCombination(char *);

int main()
{
const int maxStringSize = 26;
char thisString[maxStringSize];
cout<<"Enter String = ";
gets (thisString);
getCombination(thisString);
return 0;
}

void getCombination(char *thisString)
{
int stringSize=strlen(thisString);
for(int i = 0; i<stringSize; i++)
{
for(int j = 0; j<stringSize; j++)
{
cout<<thisString[(i+j)%stringSize];
}
cout<<"\n";
for(int k = stringSize-1; k>=0; k--)
{
cout<<thisString[(i+k)%stringSize];
}
cout<<"\n";
}
}

最佳答案

http://www.sgi.com/tech/stl/next_permutation.html

std::next_permutation 应该可以帮助您前进

关于c++ - 数组中字符的排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6394219/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com