Skip to content

Commit c99ba3a

Browse files
Merge pull request #116 from walkerrandolphsmith/feature/46-permutations
solve
2 parents c5c51d4 + 6894036 commit c99ba3a

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# 46-permutations
2+
3+
## Problem Statement
4+
5+
Given an array `nums` of **distinct integers**, return **all possible permutations** of the array.
6+
You can return the answer in **any order**.
7+
8+
### Example 1:
9+
10+
**Input:**
11+
`nums = [1, 2, 3]`
12+
13+
**Output:**
14+
`[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]`
15+
16+
### Example 2:
17+
18+
**Input:**
19+
`nums = [0, 1]`
20+
21+
**Output:**
22+
`[[0,1],[1,0]]`
23+
24+
### Example 3:
25+
26+
**Input:**
27+
`nums = [1]`
28+
29+
**Output:**
30+
`[[1]]`
31+
32+
### Constraints:
33+
34+
- `1 <= nums.length <= 6`
35+
- `-10 <= nums[i] <= 10`
36+
- All the integers of `nums` are **unique**

leet-code/46-permutations/index.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number[][]}
4+
*/
5+
var permute = function(nums) {
6+
const backtrack = (start) => {
7+
if (start === nums.length) {
8+
res.push([...nums]);
9+
return;
10+
}
11+
12+
for (let i = start; i < nums.length; i++) {
13+
[nums[start], nums[i]] = [nums[i], nums[start]];
14+
backtrack(start + 1);
15+
[nums[start], nums[i]] = [nums[i], nums[start]];
16+
}
17+
};
18+
19+
const res = [];
20+
backtrack(0);
21+
return res;
22+
};

0 commit comments

Comments
 (0)