data-structures · intermediate · ~15 min
Count fixed-size subsets hitting a sum, by backtracking.
Implement:
int count_k_subset_sum(const int *a, int n, int k, int target);
Count subsets of exactly k elements of the non-negative a[0..n-1] that sum to target, via backtracking.
Non-negative a, n, k, target.
Number of qualifying subsets.
Prune when not enough elements remain.
#include <stddef.h>
/* Count subsets of EXACTLY k elements of a[0..n-1] (non-negative) that sum to target, via backtracking. */
int count_k_subset_sum(const int *a,int n,int k,int target){ (void)a;(void)n;(void)k;(void)target; return 0; }
Forgetting the size constraint (that's plain subset-sum); not pruning.
k==0 counts 1 iff target==0.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.