data-structures · intermediate · ~15 min
Count ordered sums that make n.
Implement:
long long count_compositions(int n);
Return the number of ordered ways to write n as a sum of positive integers (compositions). count(0)=1. 0 <= n <= 62.
n in [0,62].
Number of compositions (2^(n-1) for n>=1).
Memoize the recursion.
#include <stddef.h>
/* Number of ordered ways to write n as a sum of positive integers (compositions). count(0)=1. 0<=n<=62. */
long long count_compositions(int n){ (void)n; return 0; }
Exponential recursion without memoization; miscounting the empty case.
0 has 1 composition (the empty sum).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.