c - 我将如何使用递归来生成所有可能性?

标签 c combinatorics

假设输入是 4,那么输出应该是所有可能的 4 个字母单词,其中字母为 a 到 f。一路从aaaa到ffff。我如何通过使用递归来做到这一点?

我很抱歉没有将我对这个问题的尝试包含在我最初的问题中。有些人想知道为什么我使用递归而不是使用更简单的方法(例如 for 循环),原因是我的教授希望我们使用 for 循环来解决这个问题。

这是我这样做的尝试:

void allPossiblilities(int n)
{
     char*result;
     if(Done(result))/*since the last possibility will be all f I am using that as my base case*/
     {
       printf("%s",result);
       return;
     }

 /*This is where the recursive part should go but I am totally lost as to what it should be*/
}

bool Done(result)/*This function just returns true if all the array's index are f*/
{
     int i;
     bool a=true;
     for(i=0;i<=n-1;i++)
        if(result[i]!='f')
           a=false;
}
     return a;
}

最佳答案

我会给你一个提示,让你思考:

4 位数字和 10 个可能的数字 (0-9) base^digits = 10^4 = 10000 个可能的输出 0000-9999 有多少种可能性,在您的情况下,它们将 base = 6 (A-F) 和 exp = 4 ( 4 个位置)6^4 = 1296 种组合。

递归函数是如何制作的? 他们有两个步骤:

  • 基本步骤:函数不调用自身时的准则或条件(最终条件)。

  • 递归步骤:函数调用自身时的准则或条件,其结果应该更接近基本步骤。

例如著名的阶乘函数,基本步骤是返回1,递归步骤是第二步。

PD:我试图让你自己分析问题并找到解决方案,并给你一些工具。

recursive example

代码:

#include <stdio.h>
#include <stdlib.h>

void recurs( int * s );
void print( int * s );

int main( void )
{
    int a[] = { 0, 0, 0, 0 };
    print( a );
    recurs( a );

}

void recurs( int * s )
{
    int i;

    /*Basic Case*/
    if( s[ 3 ] == 5 && s[ 2 ] == 5 && s[ 1 ] == 5 && s[ 0 ] == 5 ){
        print( s );
        printf( "\nAccomplisshed!\n" );
    }

    else{
        s[ 0 ] += 1;
        for( i = 0; i < 3; i++ ){
            if( s[ i ] == 6 ){
                s[ i ] = 0;
                s[ i + 1 ] += 1;
            }
        }
        print( s );
        recurs( s );
    }
}

/* This only prints. */
void print( int * s )
{
    int i; 
    printf( "    " );
    for( i = 3; i >= 0; i-- ){
        printf( "%c", ( s[ i ] + 65 ) );
    }
}

部分输出: enter image description here

关于c - 我将如何使用递归来生成所有可能性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13370656/

相关文章:

c - 如何从指向 C 中指针的指针获取单个字符?

c - 带有表 C 的 While 循环

algorithm - 寻找用于按字典顺序访问多重集的所有 k 组合的非递归算法

java - 计算两个给定的具有相同属性的二进制数之间存在多少个具有 X 个 1 位的二进制数

python - Python 中的组合学

algorithm - 给定字符串的所有可能组合

algorithm - 最大化由乘积之和组成的方程,然后用一个数取模

c - 如何在不读取数据的情况下监听socket?

c - 没有递归的二叉搜索树插入 C

c - 将 Win32 串行 (RS232) 通信移植到 POSIX