Tags

  • AWS (7)
  • Apigee (3)
  • ArchLinux (5)
  • Array (6)
  • Backtracking (6)
  • BinarySearch (6)
  • C++ (19)
  • CI&CD (3)
  • Calculus (2)
  • DesignPattern (43)
  • DisasterRecovery (1)
  • Docker (8)
  • DynamicProgramming (20)
  • FileSystem (11)
  • Frontend (2)
  • FunctionalProgramming (1)
  • GCP (1)
  • Gentoo (6)
  • Git (15)
  • Golang (1)
  • Graph (10)
  • GraphQL (1)
  • Hardware (1)
  • Hash (1)
  • Kafka (1)
  • LinkedList (13)
  • Linux (27)
  • Lodash (2)
  • MacOS (3)
  • Makefile (1)
  • Map (5)
  • MathHistory (1)
  • MySQL (21)
  • Neovim (10)
  • Network (66)
  • Nginx (6)
  • Node.js (33)
  • OpenGL (6)
  • PriorityQueue (1)
  • ProgrammingLanguage (9)
  • Python (10)
  • RealAnalysis (20)
  • Recursion (3)
  • Redis (1)
  • RegularExpression (1)
  • Ruby (19)
  • SQLite (1)
  • Sentry (3)
  • Set (4)
  • Shell (3)
  • SoftwareEngineering (12)
  • Sorting (2)
  • Stack (4)
  • String (2)
  • SystemDesign (13)
  • Terraform (2)
  • Tree (24)
  • Trie (2)
  • TwoPointers (16)
  • TypeScript (3)
  • Ubuntu (4)
  • Home

    [LeetCode 46] Permutations

    Published Jan 08, 2022 [  Backtracking  ]

    Problem

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

    Example 1:

    Input: nums = [1,2,3]
    Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
    

    Example 2:

    Input: nums = [0,1]
    Output: [[0,1],[1,0]]
    

    Example 3:

    Input: nums = [1]
    Output: [[1]]
    

    Constraints:

    • 1 <= nums.length <= 6
    • -10 <= nums[i] <= 10
    • All the integers of nums are unique.

    Thoughts

    • If nums only has one element, we can just return the result
    • If nums has more than one element, we can remove first element, find permutations of the remaining elements, add the removed element back, then we have one result.
      • We need do above operation n times.

    TypeScript

    function permute(nums: number[]): number[][] {
        let res: number[][] = [];
    
        if(nums.length === 1) {
            return [[...nums]]
        }
    
        // for an array of lenght n, loop n times.
        for(let i of nums){
            // remove the first value
            const first: number = nums.shift()
            // get permutation of remaining array
            const perms: number[][] = permute(nums)
            // add first value back
            for(let perm of perms){
                perm.push(first)
            }
            // update result
            res.push(...perms)
            // move first value to the back
            nums.push(first)
        }
        return res;
    };
    
    

    Reference