I have written a function for partitioning a number:
var combinations = function (i) {
var mem = [];
function inner(n, r, m) {
for (var k = m; k <= n; k++) {
if (k == n) {
r.push(k);
mem[r] = 1;
return mem;
}
else {
var copy = r.slice(0);
copy.push(k);
inner(n - k, copy, k);
}
}
}
return inner(i, [], 1);
}
In second step I would like to add a memoization to this algorithm, but can't think of implementing it the right way, beause there is no return statement until the very end (when return is specified e.g. in faactorial or fibbinacci I can add the memoization). Can anybody drive me to the right direction?
[edit] I need this algorithm to be as fast as possible. This is a competition for a kata at codewars: link There is a requirement it must be executed under 6000ms for input up to 330. That's the best algorithm I can think of, except how to store the partial results.
n, r, mrepresent?