-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathProblem96.js
57 lines (50 loc) · 1.2 KB
/
Problem96.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
49
50
51
52
53
54
55
56
57
// Problem 96
//
// This problem was asked by Microsoft.
//
// Given a number in the form of a list of digits, return all possible permutations.
//
// For example, given [1,2,3], return [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]].
//
// https://leetcode.com/problems/permutations/
//
// O(N!) Time complexity
// O(N) Space complexity
// N is the number of elements in the array
/**
* Return all possible permutations
* @param {number[]} nums
* @return {number[][]}
*/
function permutation(nums) {
if (nums.length === 0) return [];
const list = [];
backtrack(nums, list, [], new Set());
return list;
}
/**
* Recursive backtracking helper function
* @param {number[]} nums
* @param {number[][]} list
* @param {number[]} listSoFar
* @param {Set<number>} set
*/
function backtrack(nums, list, listSoFar, set) {
if (listSoFar.length === nums.length) {
list.push([...listSoFar]);
return;
}
for (let i = 0; i < nums.length; i++) {
const num = nums[i];
if (set.has(num)) continue;
// choose
listSoFar.push(num);
set.add(num);
// explore
backtrack(nums, list, listSoFar, set);
// unchoose
listSoFar.pop();
set.delete(num);
}
}
export default permutation;