-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpermute.ts
38 lines (30 loc) · 1003 Bytes
/
permute.ts
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
type Permute = (nums: number[]) => number[][];
/**
* Accepted
*/
export const permute: Permute = (nums) => {
const result: number[][] = [];
const selected: boolean[] = Array(nums.length).fill(false);
function backtrack(currentPermutation: number[]) {
// If the current permutation's length equals the input array's length, we have a complete permutation
if (currentPermutation.length === nums.length) {
result.push([...currentPermutation]);
return;
}
// Traverse the available numbers
for (let i = 0; i < nums.length; i++) {
// Skip if the number has already been selected (pruning)
if (selected[i]) continue;
// Make a choice
currentPermutation.push(nums[i]);
selected[i] = true;
// Recursively make the next choice
backtrack(currentPermutation);
// Undo the choice (backtrack)
currentPermutation.pop();
selected[i] = false;
}
}
backtrack([]); // Start backtracking
return result;
};