ProgrammingHardTCS NQT · Infosys

How many subsets of {1, 2, 3, 4, 5} sum to 6? Compute with this recursive program.

How many subsets of {1, 2, 3, 4, 5} sum to 6? Compute with this recursive program.
#include <stdio.h>
int v[5] = {1, 2, 3, 4, 5};
int cnt(int i, int s) {
    if (s == 0) return 1;
    if (s < 0 || i == 5) return 0;
    return cnt(i + 1, s - v[i]) + cnt(i + 1, s);
}
int main(void) {
    printf("%d", cnt(0, 6));
}
  1. A. 2
  2. B. 4
  3. C. 3
  4. D. 5

Correct answer: C. 3

The subsets are {1, 5}, {2, 4} and {1, 2, 3}. The recursion decides for each element whether to include it.

More C Programming questions

Exams that ask this topic