46_ Permutations

[Medium][Backtracking]

Given a collection of distinct integers, return all possible permutations.

Example:

Input: [1,2,3]

Output:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]

Solution: Backtracking

Idea:

  • Think this problems as a tree problem, put one integer in each layer and do a depth-first-search to get all the paths.

  • When we generate the tree, we do depth first.

  • Change the positions of integers so that we can create each permutation in place.

Time Complexity: O(n×n!)O(n \times n!) because there are O(n!)O(n!) permutations/paths, and on each node we have constant computation, thus for each path, there are O(n)O(n) computations.

Space Complexity: O(1)O(1)

Last updated

Was this helpful?