假设输入是 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:我试图让你自己分析问题并找到解决方案,并给你一些工具。
代码:
#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 ) );
}
}
部分输出:
关于c - 我将如何使用递归来生成所有可能性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13370656/