Skip to content

Latest commit

 

History

History
32 lines (27 loc) · 915 Bytes

File metadata and controls

32 lines (27 loc) · 915 Bytes

Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.

Screen Shot 2021-09-17 at 2 33 05 PM

/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var permute = function(nums) {
    let res = [];
    
    function dfs(nums, path, used, stack) {
        if(path.length === nums.length) {
            stack.push([...path]);
            return;
        }
        for(let i = 0; i < nums.length; i++) {
            if(used[i]) continue;
            path.push(nums[i]);
            used[i] = true;
            dfs(nums, path, used, stack);
            path.pop();
            used[i] = false;
        }
    }
    
    dfs(nums, [], Array(nums.length).fill(false), res);
    return res;
};