Skip to content

Instantly share code, notes, and snippets.

@wintercn
Last active June 7, 2017 08:28
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 wintercn/6b732691dbb577d023e91337f38b05a9 to your computer and use it in GitHub Desktop.
Save wintercn/6b732691dbb577d023e91337f38b05a9 to your computer and use it in GitHub Desktop.
var mSum = (m, n, a) =>
a.length ? m > 2 ? mSum(m, n, a.slice(0, a.length - 1)).concat(
mSum(m - 1 , n - a[a.length - 1], a.slice(0, a.length - 1)).map(e => e.concat([a[a.length - 1]]))) :
twoSum(n, a) :
[];
var twoSum = (n, a) => {
a.sort((x, y) => x - y);
var r = [];
if(a.length < 2) return r;
for(var i = 0, j = a.length - 1; i < j;) {
if(a[i] + a[j] == n)
r.push([a[i], a[j]]),
i++;
if(a[i] + a[j] > n )
j--;
if(a[i] + a[j] < n )
i++;
}
return r;
}
mSum(3, 10, [1, 2, 3, 4, 5, 6, 7, 8])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment