46. Permutations
Tags:
Medium
Skills:
backtrack
June 24, 2025
04:32 AM
No headings found
Loading content...
Related Posts
Leetcode
No headings found
Related Posts
Leetcode
Problem
Đề bài cho một mảng số nguyên nums gồm các phần tử duy nhất. Nhiệm vụ của bạn là trả về tất cả các hoán bị (permutations) có thể của mảng đó
Approach
Time and space complexity
Solution
1function permute(nums: number[]): number[][] {
2 let res: number[][] = [];
3
4 function backtrack(path: number[], visisted: Set<number>): void {
5 if (path.length === nums.length) {
6 res.push([...path]);
7 return;
8 }
9
10 for (const num of nums) {
11 if (visisted.has(num)) continue
12 path.push(num);
13 visisted.add(num)
14 backtrack(path, visisted)
15 path.pop()
16 visisted.delete(num)
17 }
18 }
19
20 backtrack([], new Set())
21 return res
22};