Given a collection of distinct integers, return all possible permutations.
Example:
Input: [1,2,3]
Output:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
/**
* @param {number[]} nums
* @return {number[][]}
*/
var permute = function(nums) {
const result = [];
const size = nums.length;
const permutations = function (current = [], remaining = []) {
if (current.length >= size) {
result.push(current.slice());
}
for (let i = 0; i < remaining.length; i++) {
current.push(remaining[i]);
permutations(current.slice(), remaining.slice(0, i).concat(remaining.slice(i + 1)));
current.pop();
}
}
permutations([], nums);
return result;
};
Runtime: 68 ms, faster than 99.84% of JavaScript online submissions forPermutations.
Memory Usage: 37.4 MB, less than 24.41% of JavaScript online submissions forPermutations.