Skip to content

Instantly share code, notes, and snippets.

@uinz
Last active July 25, 2018 08:51
Show Gist options
  • Save uinz/0e3cd2208b1d97761f09a8ec1366564f to your computer and use it in GitHub Desktop.
Save uinz/0e3cd2208b1d97761f09a8ec1366564f to your computer and use it in GitHub Desktop.
求给定数组 arr, 求 和为 num 的组合
function sum(arr: number[]) {
return arr.reduce((r, n) => r + n, 0);
}
function group(arr: number[], num: number) {
const result = [];
(function loop(unselectedList = [], selectedList = []) {
if (unselectedList.length === 0) {
return;
}
unselectedList.forEach((_, i) => {
const newSelectedList = selectedList.concat(unselectedList[i]);
const valueOfSum = sum(newSelectedList);
if (valueOfSum >= num) {
if (valueOfSum === num) {
result.push(newSelectedList);
}
return;
}
const newUnselectedList = unselectedList.filter((_, j) => j > i);
loop(newUnselectedList, newSelectedList);
});
})(arr);
return result;
}
group([1, 2, 3, 4], 3) // [[1,2], [3]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment