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



同样,如果我输入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应该可以帮助您

10-04 16:28