Skip to content

Instantly share code, notes, and snippets.

@chmllr
Created June 13, 2015 18:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chmllr/5bd14f27d2472092bd2a to your computer and use it in GitHub Desktop.
Save chmllr/5bd14f27d2472092bd2a to your computer and use it in GitHub Desktop.
var combinationSum = function (candidates, target) {
candidates.sort(function (a, b) { return a - b });
var C = {};
var f = function (n) {
if (n in C) return C[n];
var result = [];
if (n > 0)
candidates.forEach(function (cand) {
if (n == cand) result.push([cand]);
else f(n - cand).forEach(function (comb) {
if (cand <= comb[0])
result.push([cand].concat(comb));
})
});
return C[n] = result;
};
return f(target);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment