Skip to content

Latest commit

 

History

History
37 lines (30 loc) · 1.05 KB

File metadata and controls

37 lines (30 loc) · 1.05 KB

Screen Shot 2022-09-18 at 22 49 22

/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var permuteUnique = function(nums) {
    let res = [];
    
    // Sort the array to make sure we can skip the same value.
    nums.sort((a, b) => a - b);
    
    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;
            // When a number has the same value with its previous, we can use this number only if its previous is used
            if(i > 0 && nums[i] === nums[i - 1] && !used[i - 1]) 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;
};