Permutations in TypeScript

function permute(nums: number[]): number[][] {
    // Result array to store all the permutations
    let result: number[][] = [];

    // Recursive function to generate permutations
    function backtrack(start: number) {
        // Base case: If the current permutation is complete
        if (start === nums.length) {
            // Push a copy of nums, since nums will be modified in-place
            result.push(nums.slice());
            return;
        }

        for (let i = start; i < nums.length; i++) {
            // Swap the current element with the start element
            [nums[start], nums[i]] = [nums[i], nums[start]];
            // Continue generating permutations with the next element as the start
            backtrack(start + 1);
            // Backtrack: Undo the previous swap
            [nums[start], nums[i]] = [nums[i], nums[start]];
        }
    }

    // Start generating permutations from the first element
    backtrack(0);

    // Return all generated permutations
    return result;
}

PrevNext