Permutations
Difficulty: Medium · Pattern: Backtracking · LeetCode #46
Return every ordering (permutation) of an array of distinct integers. The list of permutations may be in any order.
Examples
text
nums = [1, 2, 3] → [[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]]
nums = [4, 7] → [[4,7], [7,4]]Hints
- A permutation is complete when it has n elements.
- At each position, any element not yet used can go next. Track usage with a boolean array.
Approach
Backtrack over positions: keep a path and a used array. If path has length n, record a copy. Otherwise, for each unused index, mark it used, append, recurse, then undo both. There are n! leaves, each copied in O(n).
(An in-place alternative swaps nums[start] with each nums[i ≥ start], recurses on start + 1, and swaps back.)
Complexity
Time: O(n · n!). Space: O(n) recursion plus the used array.
Python solution
def permute(nums):
res, path, used = [], [], [False] * len(nums)
def bt():
if len(path) == len(nums):
res.append(path[:])
return
for i, x in enumerate(nums):
if used[i]:
continue
used[i] = True
path.append(x)
bt()
path.pop()
used[i] = False
bt()
return resJavaScript solution
function permute(nums) {
const res = [], path = [], used = new Array(nums.length).fill(false);
const bt = () => {
if (path.length === nums.length) { res.push([...path]); return; }
for (let i = 0; i < nums.length; i++) {
if (used[i]) continue;
used[i] = true; path.push(nums[i]);
bt();
path.pop(); used[i] = false;
}
};
bt();
return res;
}