LeetCode 46. Permutations
Question
Given an array nums
of distinct integers, return all the possible permutations. You can return the answer in any order.
Example 1:
Example 2:
Example 3:
Constraints:
1 <= nums.length <= 6
-10 <= nums[i] <= 10
- All the integers of
nums
are unique.
Source: https://leetcode.com/problems/permutations/
Solution
A conveninent condition provided by this question is that all elements are distinct. Thus, we do not need to consider duplicates of result.
The following solution is based on swap()
so that it does not require additional space to store intermediate result of permutations. The idea is similar to selection sort. We treat elements before position
as a determined permutation prefix, treat element after position
as available elements in future searches. Another point is backtracking. Because all operations are on the same array nums
, we need to recover changes of subtrees before diving into another path.
A common trick for DFS problems is to draw a DFS tree.

1 | private void swap(int[] nums, int i, int j) { |
LeetCode 46. Permutations