Overview
Given an array nums of distinct integers, return all possible permutations in any order.
Constraints
1 <= nums.length <= 6-10 <= nums[i] <= 10- All integers are unique.
Examples
permute([1, 2, 3]); // => [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] permute([1]); // => [[1]]
Solution
Reveal solution
function permute(nums) {
const result = [];
function backtrack(path, used) {
if (path.length === nums.length) { result.push([...path]); return; }
for (let i = 0; i < nums.length; i++) {
if (used[i]) continue;
used[i] = true;
path.push(nums[i]);
backtrack(path, used);
path.pop();
used[i] = false;
}
}
backtrack([], new Array(nums.length).fill(false));
return result;
}Resources
permutations.js
Permutations
mediumcodingAlgorithmsBacktracking
Overview
Given an array nums of distinct integers, return all possible permutations in any order.
Constraints
1 <= nums.length <= 6-10 <= nums[i] <= 10- All integers are unique.
Examples
permute([1, 2, 3]); // => [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] permute([1]); // => [[1]]
Solution
Reveal solution
function permute(nums) {
const result = [];
function backtrack(path, used) {
if (path.length === nums.length) { result.push([...path]); return; }
for (let i = 0; i < nums.length; i++) {
if (used[i]) continue;
used[i] = true;
path.push(nums[i]);
backtrack(path, used);
path.pop();
used[i] = false;
}
}
backtrack([], new Array(nums.length).fill(false));
return result;
}Resources
NameTopicDifficulty
103 of 103 problems