15% off all plans & roadmaps Use code
See plansLeetCode 46 · Solution & editorial
Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.
Permutations is a Backtracking Patterns problem, in the Permutations subpattern. The pattern covers subsets, permutations, combinations, N-Queens, and word search
Generate all permutations using backtracking. Handle duplicates and next permutation.
The reference solution runs in O(n * n!) time and O(n * n!) space.
Permutations has been reported in interviews at Amazon, Apple, Bloomberg, ByteDance, eBay, Facebook, Google, LinkedIn.
The full editorial is part of Pro
It explains the core insight, the complexity analysis and the common mistakes, with a worked solution.
Permutations is a Backtracking Patterns problem, in the Permutations subpattern. Once the approach above makes sense, write it yourself and then work through the neighbouring problems that reuse it.