我的函数获取一个字符数组,大小,当前位置和计数器。
我需要它在输入的尺寸长度内打印A,B,C的所有可能组合(无AA和无CCC)。
当size大于3时,该函数的值返回一个我没有找到原因的非合理值。

int abc(char arr[],int lastPlace,int curPlace,int count){
    if (curPlace == lastPlace){
        arr[curPlace] = '\0';
        printf("%s, ", arr);
        return 1;
    }
    if(!curPlace || arr[curPlace - 1] != 'A'){
        arr[curPlace] = 'A';
        count += abc(arr, lastPlace, curPlace + 1, 0);
    }
    arr[curPlace] = 'B';
    count += abc(arr, lastPlace, curPlace + 1, 0);
    if(curPlace < 2 || arr[curPlace - 1] != 'C' || arr[curPlace - 2] != 'C'){
        arr[curPlace] = 'C';
        count+=abc(arr, lastPlace, curPlace + 1, 0);
        if (curPlace == 0)
            return count;
    }
}

最佳答案

int abc(char arr[], int lastPlace, int curPlace, int count)
{
    if (curPlace == lastPlace)
    {
        arr[curPlace] = '\0';
        printf("%s, ", arr);
        return 1;
    }
    if(!curPlace || arr[curPlace-1]!='A'){
        arr[curPlace] = 'A';
        count += abc(arr, lastPlace, curPlace + 1, 0);
    }

    arr[curPlace] = 'B';
    count += abc(arr, lastPlace, curPlace + 1, 0);

    if(curPlace < 2 || arr[curPlace - 1] != 'C' || arr[curPlace - 2] != 'C')
    {
        arr[curPlace] = 'C';
        count += abc(arr, lastPlace, curPlace + 1, 0);
    }
    return count;
}

09-12 19:58