#46

Permutations

Medium
ArrayBacktrackingBacktrackingRecursion
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n!)
O(n!)
Space
O(n)
O(n)
💡

Intuition

Time O(n!)Space O(n)

The optimal solution leverages backtracking to efficiently explore all permutations without unnecessary swaps. This method is similar to the brute force but avoids redundant operations.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a result list to store permutations.
  2. 2Step 2: Create a backtracking function that takes the current permutation and a set to track used elements.
  3. 3Step 3: If the current permutation length equals the input array length, add it to the result.
  4. 4Step 4: Iterate through the input array, adding unused elements to the current permutation and marking them as used.
solution.py17 lines
1def permute(nums):
2    def backtrack(path, used):
3        if len(path) == len(nums):
4            result.append(path[:])
5            return
6        for i in range(len(nums)):
7            if used[i]: continue
8            used[i] = True
9            path.append(nums[i])
10            backtrack(path, used)
11            path.pop()
12            used[i] = False
13
14    result = []
15    used = [False] * len(nums)
16    backtrack([], used)
17    return result

Complexity note: The time complexity remains O(n!) due to the number of permutations. The space complexity is O(n) for the recursion stack and the path storage.

  • 1Understanding backtracking is crucial for generating permutations.
  • 2Recognizing when to use a used array can optimize the solution.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.