获得帮助递归C编程

时间:2015-10-27 14:59:03

标签: c recursion subsequence

给定长度为n数组,并且要求将程序编写为计算 子序列数 该给定数组的长度m

以下是执行此操作的代码。请看看。

int recCountSubseq(int seqLength, int length, int s[]) {
    int answer;

    if (seqLength == 0) {       /* Base case: found a subseq of correct length */
        return 1;
    }

    if (seqLength >= length) {  /* Base case: only possible is seqLength == length*/
        return (seqLength==length);
    }

    /* Recursive case: two branches */
    answer = recCountSubseq(seqLength-1, length-1, s); /* s[length-1] is in subseq*/
    printf("answer=%d\n", answer);

    answer += recCountSubseq(seqLength, length-1, s);  /* s[length-1] is not in subseq */
    printf("increased answer is %d\n", answer);

    return answer;
}

void countSubseq(int seqLength, int length, int s[]) {    
    printf("#subseq = %d\n", recCountSubseq(seqLength, length, s));    
}

int main() {
    int length;
    scanf("%d", &length);

    int seqLength;
    int i;
    int s[100];

    for (i=0;i<length; i++) {
        scanf("%d", &s[i]);
    }

    countSubseq(seqLength, length, s);

    return 0;
}

现在,我的问题:为什么seqLength的值每次都在减少,这个代码究竟是如何工作的?

2 个答案:

答案 0 :(得分:2)

该函数具有未定义的行为,因为至少变量seqLength未初始化:

int seqLength;

任务不明确。如果您有一个包含n元素的数组,那么m等于m <= n的长度为n - m + 1的连续子序列的数量。

所以编写这样的函数并没有多大意义。:)此外,我甚至看不到函数中的哪个位置存在对作为第三个参数传递的数组的访问。:)

Insetad我可以建议你以下功能。至少它有一定道理。:)

#include <stdio.h>

size_t recCountSubseq( const int a[], size_t n, size_t m )
{
    if ( m <= n )
    {
        for ( size_t i = 0; i < m; i++ ) printf( "%d ", a[i] );
        printf( "\n" );
    }

    return n <= m ? n == m : 1 + recCountSubseq( ++a, --n, m );
}

int main( void )
{
    int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    printf( "There are %zu subsequencies\n", recCountSubseq( a, sizeof( a ) / sizeof( *a ), 3 ) );

    return 0;
}

它的输出是

1 2 3 
2 3 4 
3 4 5 
4 5 6 
5 6 7 
6 7 8 
7 8 9 
There are 7 subsequencies

我认为您错误地解释了作业及其解决方案。你应该重新检查他们的描述。

答案 1 :(得分:0)

根据我的理解,您需要从用户那里获得子序列的长度,这在您的代码中没有完成。

如果我的猜测是正确的,那么main()函数将如下所示:

int main(array<System::String ^> ^args)
{
  int length;

  printf("Length of array:");
  scanf("%d", &length);

  int seqLength;

  printf("Length of sub-seq:");
  scanf("%d", &seqLength);

  int i;
  int s[100];

  printf("Array of %d elements:", length);
  for (i=0;i<length; i++)
  {
    scanf("%d", &s[i]);
  }

  countSubseq(seqLength, length, s);

  return 0;
}