AAlgoLoopSpaced repetition for LeetCode
MEDIUMBacktrackingLeetCode ↗

Permutations

The key idea

Build each permutation one slot at a time. At every slot try every number not yet used, recurse, then undo that choice (backtrack) so the next branch can reuse it. The used set is what keeps each number to one appearance per permutation.

Problem

Given an array nums of distinct integers, return all the possible permutations. You may return the answer in any order.

A permutation is an arrangement of nums that uses every element exactly once; the order of elements is what differs between permutations.

Constraints

Examples

Input: nums = [1,2,3] Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
Input: nums = [0,1] Output: [[0,1],[1,0]]
Input: nums = [1] Output: [[1]]

Complexity

Time: O(n * n!) Space: O(n)

See the full solution

410310
Step-by-step visualization
Start free →

More Backtracking problems