-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path15-四数之和.js
33 lines (27 loc) · 807 Bytes
/
15-四数之和.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
const nums = [1, 0, -1, 0, -2, 2]
function getGroups(nums, length) {
const groups = new Array()
nums.sort((a, b) => a - b)
function func(group, start) {
if(group.length >= length) {
return groups.push(group)
}
for(let i = start; i < nums.length; i ++) {
func([...group, nums[i]], i + 1)
}
}
func([], 0)
return Array.from(new Set(groups.map(group => {
return group.join('*')
}))).map(group => {
return group.split('*').map(num => parseInt(num))
})
}
function getSum(nums) {
return nums.reduce((prev, current) => prev + current, 0)
}
function main(nums, target) {
const groups = getGroups(nums, 4)
return groups.filter(group => getSum(group) === target)
}
console.log(main(nums, 0))