Permutations

Given a collection of numbers, return all possible permutations.

input contains duplicate number? NO. input sorted? doesn't matter input size? < 15

Example

([1,2,3]) => [
    [1,2,3], [1,3,2],
    [2,1,3], [2,3,1],
    [3,1,2], [3,2,1]
]

3!

Analysis

How is this different from subsets?

we can use the previous candidates that are not used at this level

          []
         [1]
        /   \
    [1,2]   [1, 3]
    /          \!!! we can still add 2 here (not in subsets)
[1,2,3]     [1, 3, 2]


Think of it we are doing a bfs at each level [1, ?]

Approach

The way it exhausts the search space is slightly different than combinations. Since the order does not matter, we can reuse elements that are smaller than the current element.

Code

Time Complexity

Time = #subproblems * time/subproblem = O(n!) * O(n) = O(n*n!)

To Do

insertion iterative approach

swapping approach??

Follow Up Question (LC.47arrow-up-right)

What if the input has duplicates?

For example, given input [1, 2, 2], we have 3!2!1!\frac{3!}{2!1!} permutations (with repetition). We are eliminating 3 cases where the second '2' is swapped with the first '2'. We want [1,21,22][1, 2_1, 2_2] instead of [1,22,21][1, 2_2, 2_1]. Therefore, once the input is sorted, we need to skip the current element when it is the same as the previous element and the previous element is not used.

Last updated