I found the following problem when preparing for an interview:
3 can be written as 1+1+1, 1+2, 2+1; 4 can be written as 1+1+1+1, 1+1+2, 2+2, 1+2+1, 2+1+1, 3+1, 1+3; Given an integer, how many possible expressions exist? (1+2 and 2+1 are different)
So this is fairly straightforward to write a brute force algorithm to calculate that and get the set all the sets of numbers that do it:
private static Set<List<Integer>> getIntegersSum(int num) {
Set<List<Integer>> returnSet = new HashSet<List<Integer>>();
if (num == 0) {
returnSet.add(new LinkedList<Integer>());
return returnSet;
}
for (int i = 1; i <= num; i++) {
Set<List<Integer>> listNMinI = getIntegersSum(num - i);
for (List<Integer> l : listNMinI) {
l.add(0, i);
returnSet.add(l);
}
}
return returnSet;
}
Now I believe the recurrence relation that describes the complexity of this algorithm is:
T(0) = \Theta (1)
T(n) = O(n) + \Sum_{i=0}^{n-1} T(i)
I'm not quite sure how to arrive at big-oh complexity from this recurrence relation. I would also like to know if there is a closed form solution for the question (how many combinations like that we will have for each number).
I'm also not sure what the complexity would be if we memoize this algorithm by caching the results of each call (similarly to how you can speed up fibonacci).