-
Notifications
You must be signed in to change notification settings - Fork 0
/
18.js
49 lines (44 loc) · 1.13 KB
/
18.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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/*
* @lc app=leetcode.cn id=18 lang=javascript
*
* [18] 四数之和
*/
// @lc code=start
/**
* @param {number[]} nums
* @param {number} target
* @return {number[][]}
*/
var fourSum = function(nums, target) {
const list = [];
nSum(5,0,nums.sort((a,b) => a-b),target,list)
console.log('list-----',list)
return list
};
var nSum = function (n,fromIndex,nums,target,list,tempr=[]) {
if (n == 2) {
let a = fromIndex
let b = nums.length-1
console.log('------',tempr)
while (a < b) {
let sum = nums[a] + nums[b]
if (sum < target) {
a++
} else if (sum > target) {
b--
} else {
list.push([...tempr,nums[a],nums[b]])
console.log('获取到一个:',fromIndex,target,tempr)
return tempr
}
}
return []
}
for (let j = fromIndex; j < nums.length; j++) {
fromIndex == 0 && (tempr = []);
tempr.push(nums[j])
nSum(n-1,j+1,nums,target - nums[j],list,tempr)
}
}
fourSum([1,0,-1,3,-3,0,-2,2],0)
// @lc code=end