在C中搜索唯一元素组合的算法(结果字符串中的元素位置无关紧要)

问题描述 投票:2回答:1

我有char数组唯一元素搜索的代码。但它工作不正确。例如,在“ABCD”数组的情况下,我失去了“ABD”的情况。我该如何解决?

#include <stdio.h>
#include <string.h>

void     fun(char *str, int size, int depth)
{
    int i = 0;
    int j = 0;
    int k = 0;
    while (i < size - depth + 1)
    {
        j = i + 1;
        while (j < size - depth + 2)
        {
            printf("%c", str[i]);
            k = j;
            while (k < j + depth - 1)
            {
                printf("%c", str[k]);
                k++;
            }
            printf("\n");
            j++;
        }
        i++;
    }
}

int     main(void)
{
    char    *str = "ABCD";
    int i = 0;
    while (i < strlen(str))
    {
        fun(str, strlen(str), i + 1);
        i++;
    }
    return (0);
}

结果是:A A A B B B C C D AB AC AD BC BD CD ABC ACD BCD ABCD

我需要:A B C D AB AC AD BC BD CD ABC ABD ACD BCD ABCD

因此,你可以看到有几个错误 - 在开始时重复单个字符并且缺少ABD情况。如果字符串是“ABCDE”,则会丢失更多变体。

c algorithm
1个回答
0
投票

此代码应解决此问题:

#include <string.h>
#include <stdio.h>

void fun(char *str, char *data, int start, int end, int idx, int depth)
{
    if (idx == depth)
    {
        for (int j = 0; j < depth; j++)
            printf("%c", data[j]);
        printf("\n");
        return;
    }
    for (int i = start; i <= end && end - i + 1 >= depth - idx; i++)
    {
        data[idx] = str[i];
        fun(str, data, i + 1, end, idx + 1, depth);
    }
}

int main()
{
    char *str = "ABCD";
    int i = 0;

    while (i < strlen(str))
    {
        char data[i + 1];
        fun(str, data, 0, strlen(str) - 1, 0, i + 1);
        i++;
    }
    return (0);
}

输出:

A B C D AB AC AD BC BD CD ABC ABD ACD BCD ABCD

并且也适用于“ABCDE”等。

© www.soinside.com 2019 - 2024. All rights reserved.