给定一个长度为 的数组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
每次减少的价值,以及这段代码究竟是如何工作的?