Permutations
Problem
Given an array of distinct integers, return every ordering of its elements. Each permutation uses every element exactly once, and the list of permutations may be in any order.
Examples
Constraints
- • 1 <= nums.length <= 6
- • All elements are distinct
Hints & approach
Hint 1
Fill positions left to right; each position can take any element not yet used.
Hint 2
Track which elements are already in the current path with a boolean array.
Hint 3
Alternatively, swap each candidate into the current position and recurse on the rest.
Approachtry the hints first
Keep a current path and a used[] flag per element. At each level loop over all elements; skip used ones, otherwise mark it, append it, recurse, then unmark and remove it. When the path length equals n, save a copy. The in-place variant swaps nums[i] with nums[start] for each i >= start, recurses on start + 1, and swaps back, which avoids the extra flag array.
Time O(n * n!) · Space O(n) recursion, excluding output