Skip to content

Commit 4f08ac4

Browse files
committed
Add solution #46
1 parent d2431fa commit 4f08ac4

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@
3939
41|[First Missing Positive](./0041-first-missing-positive.js)|Hard|
4040
42|[Trapping Rain Water](./0042-trapping-rain-water.js)|Hard|
4141
43|[Multiply Strings](./0043-multiply-strings.js)|Medium|
42+
46|[Permutations](./0046-permutations.js)|Medium|
4243
49|[Group Anagrams](./0049-group-anagrams.js)|Medium|
4344
50|[Pow(x, n)](./0050-powx-n.js)|Medium|
4445
53|[Maximum Subarray](./0053-maximum-subarray.js)|Easy|
@@ -216,4 +217,4 @@
216217

217218
[MIT License](https://opensource.org/licenses/MIT)
218219

219-
Copyright (c) 2019-2021 [Josh Crozier](https://joshcrozier.com)
220+
Copyright (c) 2019-2022 [Josh Crozier](https://joshcrozier.com)

solutions/0046-permutations.js

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* 46. Permutations
3+
* https://leetcode.com/problems/permutations/
4+
* Difficulty: Medium
5+
*
6+
* Given an array nums of distinct integers, return all the possible permutations.
7+
* You can return the answer in any order.
8+
*/
9+
10+
/**
11+
* @param {number[]} nums
12+
* @return {number[][]}
13+
*/
14+
var permute = function(nums) {
15+
const result = [];
16+
backtrack(result, nums);
17+
return result;
18+
};
19+
20+
function backtrack(result, nums, order = []) {
21+
if (!nums.length) {
22+
result.push(order);
23+
} else {
24+
for (let i = 0; i < nums.length; i++) {
25+
backtrack(
26+
result,
27+
[...nums.slice(0, i), ...nums.slice(i + 1)],
28+
[...order, nums[i]]
29+
);
30+
}
31+
}
32+
}

0 commit comments

Comments
 (0)