如何输出一个字符串的所有组合

方法一:递(sangxin)归(bingkuang)法,遍历字符串,每个字符只能取或不取。取该字符的话,就把该字符放到结果字符串中,遍历完毕后,输出结果字符串。

代码如下:

#include "stdafx.h"
#include <stdio.h>
#include <string.h>
void CombineRecursiveImpl(const char* str, char* begin, char* end)
{
    if (*str == 0)
    {
        *end = 0;
        if (begin != end)
            printf("%s", begin);
        return;
    }
    CombineRecursiveImpl(str + 1, begin, end);
    *end = *str;
    CombineRecursiveImpl(str + 1, begin, end + 1);
}
void CombineRecursive(const char str[])
{
    if (str == NULL)
        return;
    const int MAXLENGTH = 64;
    char result[MAXLENGTH];
    CombineRecursiveImpl(str, result, result);
}
int main()
{
    CombineRecursive("abc");
    printf("\n");
    getchar();
    return 0;
}

    效果如图:

    方法二:字符串构造法,即构造一个长度为n的01字符串表示输出结构中是否包含某个字符。这需要两层循环,外层循环表示每个组合,内层循环表示每个组合分别取哪些字符。

代码如下:

#include "stdafx.h"
#include <stdio.h>
#include <string.h>
void Combine(const char str[])
{
    if (str == NULL || *str == 0)
        return;
    const int MAXLENGTH = 64;
    int len = strlen(str);
    bool used[MAXLENGTH] = { 0 };
    char cache[MAXLENGTH];
    char *result = cache + len;
    *result = 0;
    while (1)
    {
        int index = 0;
        while (used[index])
        {
            used[index] = false;
            result++;
            index++;
            if (index == len)
                return;
        }
        used[index] = true;
        result--;
        *result = str[index];
        printf("%s ", result);
    }
}
int main()
{
    Combine("abc");
    printf("\n");
    getchar();
    return 0;
}

    效果如图:

posted @ 2014-03-25 10:23  源子陌  Views(1932)  Comments(0Edit  收藏  举报