Last active
July 25, 2018 08:51
-
-
Save uinz/0e3cd2208b1d97761f09a8ec1366564f to your computer and use it in GitHub Desktop.
求给定数组 arr, 求 和为 num 的组合
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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