-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0090. Subsets II.js
42 lines (37 loc) · 998 Bytes
/
0090. Subsets II.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
// Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).
// Note: The solution set must not contain duplicate subsets.
// Example:
// Input: [1,2,2]
// Output:
// [
// [2],
// [1],
// [1,2,2],
// [2,2],
// [1,2],
// []
// ]
// 1) 回溯
/**
* @param {number[]} nums
* @return {number[][]}
*/
var subsetsWithDup = function(nums) {
let list = []
const backtrack = (list, tempList, nums, start) => {
list.push([...tempList])
for (let i = start; i < nums.length; i++) {
if (i > start && nums[i] === nums[i - 1]) {
continue
}
tempList.push(nums[i])
backtrack(list, tempList, nums, i + 1)
tempList.pop()
}
}
nums = nums.sort((a, b) => a - b)
backtrack(list, [], nums, 0)
return list
}
// Runtime: 64 ms, faster than 74.95% of JavaScript online submissions for Subsets II.
// Memory Usage: 36.4 MB, less than 10.00% of JavaScript online submissions for Subsets II.