[LeetCode] Permutations and Permutations II (Java)

Permutations

Given a collection of numbers, return all possible permutations.

For example,
[1,2,3] have the following permutations:
[1,2,3][1,3,2][2,1,3][2,3,1][3,1,2], and [3,2,1].

Permutations II

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

For example,
[1,1,2] have the following unique permutations:
[1,1,2][1,2,1], and [2,1,1].

Analysis

It’s easy to implement Permutation recursively. In every level we use a for loop to pick any entry in the array, delete it from the array, and then do this recursively until the array is empty. Now we have a permutation and add it to the result list.

In Permutations, we are asked to generate permutations for an array, in which there is no duplicates. But in Permutation II, the array might contains duplicates, so that if we use the code that can pass Permutations, it may generate some duplicate results, which is not allowed in this problem. We can check if the previous one is also the same value as the number we are going to put it in the permutation list. If it’s in the permutation list and the value is equal, we won’t put it in the list. We use an boolean array to save the visit status. ArrayList is also used here because we usually need to visit certain element by index.

Code

Permutations

Permutations II

Complexity

We need to generate all permutations. So the complexity is O(n!).