Permutations
The problem
Section titled “The problem”You get an array of distinct integers. Return every way to arrange all of them. Any order of the answers is fine.
nums = [1, 2, 3] -> [[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]]Key insight
Section titled “Key insight”Here order matters, so [1, 2] and [2, 1] are both wanted. That means no start index.
At every level, any number you haven’t used yet may go next.
Track what’s on the path with a used array. Each level loops over all indices, skips the
used ones, and does the usual choose, explore, un-choose. This time un-choosing has two
parts: pop the path and reset used[i]. A path is finished when its length equals n.
The tree has n choices at the top, n-1 next, and so on: n! leaves.
Show solutionHide solution
def permute(nums: list[int]) -> list[list[int]]: res, path = [], [] used = [False] * len(nums)
def backtrack() -> None: if len(path) == len(nums): res.append(path[:]) return for i in range(len(nums)): # every unused number can go next if used[i]: continue used[i] = True path.append(nums[i]) # choose backtrack() # explore path.pop() # un-choose used[i] = False
backtrack() return resexport function permute(nums: number[]): number[][] { const res: number[][] = []; const path: number[] = []; const used: boolean[] = new Array(nums.length).fill(false);
function backtrack(): void { if (path.length === nums.length) { res.push([...path]); return; } for (let i = 0; i < nums.length; i++) { // every unused number can go next if (used[i]) continue; used[i] = true; path.push(nums[i]); // choose backtrack(); // explore path.pop(); // un-choose used[i] = false; } }
backtrack(); return res;}import java.util.ArrayList;import java.util.List;
class Solution { public List<List<Integer>> permute(int[] nums) { List<List<Integer>> res = new ArrayList<>(); backtrack(nums, new boolean[nums.length], new ArrayList<>(), res); return res; }
private void backtrack(int[] nums, boolean[] used, List<Integer> path, List<List<Integer>> res) { if (path.size() == nums.length) { res.add(new ArrayList<>(path)); return; } for (int i = 0; i < nums.length; i++) { // every unused number can go next if (used[i]) continue; used[i] = true; path.add(nums[i]); // choose backtrack(nums, used, path, res); // explore path.remove(path.size() - 1); // un-choose used[i] = false; } }}Complexity
Section titled “Complexity”- Time: O(n · n!) — there are n! permutations, and copying each into the result costs O(n). The loops at inner nodes add only a constant factor on top of that.
- Space: O(n) — the path, the
usedarray and the recursion are each at most n. The output is not counted.
Watch out for
Section titled “Watch out for”- Reset
used[i]when you un-choose. Forgetting it means later branches think the number is still taken and you return too few answers. - Copy the path before adding it to the results.
- Don’t reuse the subsets template. A start index would only produce increasing orders, so you’d get just one permutation.
Variations
Section titled “Variations”Permutations II (LeetCode 47)
Section titled “Permutations II (LeetCode 47)”The array may contain duplicates; return unique permutations. The trick: sort, then
skip nums[i] if it equals nums[i - 1] and nums[i - 1] is not currently used. That
forces equal numbers to be placed in left-to-right order.
Next Permutation (LeetCode 31)
Section titled “Next Permutation (LeetCode 31)”Rearrange into the next larger ordering, in place. The trick: no backtracking. Find the rightmost ascent, swap its left value with the smallest larger value to its right, then reverse the tail.
Permutation in String (LeetCode 567)
Section titled “Permutation in String (LeetCode 567)”Does one string contain a permutation of another as a substring? The trick: you don’t generate permutations at all. Slide a window and compare letter counts.