【问题标题】:Print all combination of a string using recursion in C在 C 中使用递归打印字符串的所有组合
【发布时间】:2020-08-04 03:14:02
【问题描述】:

我有一个任务是编写代码来打印 N 字符的所有组合。例如,如果输入为 3,则预期输出必须为“aaa aab aac aba ... ccc”。但是我的代码一遍又一遍地循环。这是我的代码。

#include <stdio.h>

#ifndef MAX
#define MAX 5
#endif

void comb(char kar[], int size, int index) {
    // string = aaa
    // lim = 'd'
    char lim = 'a' + size;
    while (index != -1) {

        if (kar[size-1] != lim) { // != c
            for (int i = 0; i < size; i++) {
                printf("%s ", kar);
                kar[size-1]+=1;
            }
            return comb(kar, size, index);

        } else {

            while (kar[index-1] == lim && index != -1) {
                kar[index-1]='a';
                index--;
            }
            kar[index-1] += 1;

            return comb(kar, size, size);
        }
    }
}

int main(int argc, char const *argv[]) {
    int n;
    char kar[MAX];

    printf("Input N char : ");
    scanf(" %d", &n);

    for (int j = 0; j < n; j++) {
        kar[j] = 'a';
    }

    comb(kar, n, n);

    return 0;
}

我有点困惑,我不知道错误在哪里。谢谢。

【问题讨论】:

  • OT:提示:不要写97,而是'a'。它更易读,更清楚地表明了你的意图。
  • 稍微OT:零初始化kar数组像这样:char kar[MAX] = { 0 };,否则你很可能会打印垃圾。
  • 您只能将nindexsize 作为index 参数传递,并且您永远不会在comb 中分配给它,所以很难看出@987654330 @ 可能永远是假的。

标签: c recursion combinations


【解决方案1】:

问题已解决。我更改了comb() 中的一些元素,并添加了pow() 函数来定义递归限制。

int comb(char kar[], int size, int index, int limit) {

    char lim = 97 + size;
    int limit_value = pow(size,size);
    if(limit == limit_value){
        return 1;

    } else {

        if (index < size-1) {
            printf("%s ", kar);
            kar[size-1]+=1;
            return comb(kar, size, index+1, limit+1);

        } else {
            int cek = index;
            printf("%s ", kar);
            while (kar[cek] == lim-1 ) {
                kar[cek]=97;
                cek-=1;
            }
            kar[cek] += 1;

            return comb(kar, size, 0, limit+1);
        }
    }
}

【讨论】:

    猜你喜欢
    • 2015-03-20
    • 2017-02-17
    • 1970-01-01
    • 2020-05-03
    • 2021-10-31
    • 2012-04-07
    • 2012-04-17
    • 1970-01-01
    相关资源
    最近更新 更多