Permutations
Medium
Topics
Given an array nums of distinct integers, return all possible permutations in any order.
Example 1
All 6 orderings (3!).
Each chip is one permutation.
Input: nums = [1,2,3] Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
Example 2
Input: nums = [1] Output: [[1]]
Constraints
- 1 <= nums.length <= 6
- All integers are unique.
Editorial — intuition, approach, complexity and pitfalls
Intuition
Build a permutation position by position, choosing each unused element in turn. Backtracking with a used-marker explores all n! orderings.
Approach
- Track which elements are used.
- At each step append an unused element and recurse.
- When the path length equals n, record it, then backtrack.
Dry Run
nums = [1, 2, 3]
Unlike subsets there is no `start`: every index is a candidate at every depth, and
`used` is what stops an element appearing twice in one permutation.
take 1 used [T,F,F] path [1]
take 2 used [T,T,F] path [1,2]
take 3 used [T,T,T] path [1,2,3] complete
take 3 used [T,F,T] path [1,3]
take 2 path [1,3,2] complete
take 2 used [F,T,F] path [2]
... [2,1,3] and [2,3,1]
take 3 used [F,F,T] path [3]
... [3,1,2] and [3,2,1]
answer 1 2 3 | 1 3 2 | 2 1 3 | 2 3 1 | 3 1 2 | 3 2 1
Watch used go from [T,T,T] back to [T,F,T] between the first and second results.
That reset is the backtracking. Without `used[i] = False` on the way out, each
index is consumed once for the entire search rather than once per branch, and the
output is a single permutation: [[1, 2, 3]].
Both undos are required -- `path.pop()` and the used reset -- and they restore two
different things. Any mutation made on the way down has to be reversed on the way
up, which is the one rule that makes a shared mutable path safe to reuse across
branches.Complexity
- Time — O(n * n!): n! permutations, each built in O(n).
- Space — O(n): recursion depth and used array.
Common Pitfalls
- Unmark
used[i]on the way back out. Without it each index is consumed once for the whole search rather than once per branch, so[1,2,3]yields only1 2 3instead of all six orderings. - Both undos have to happen --
path.pop()and theusedreset. Backtracking is only correct if every mutation made on the way down is reversed on the way up.
Full Solution — all languages
class Solution:
def permute(self, nums):
res=[]
used=[False]*len(nums)
def dfs(path):
if len(path)==len(nums): res.append(path[:]); return
for i in range(len(nums)):
if used[i]: continue
used[i]=True; path.append(nums[i]); dfs(path); path.pop(); used[i]=False
dfs([])
return resimport java.util.*;
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res=new ArrayList<>();
dfs(nums,new boolean[nums.length],new ArrayList<>(),res);
return res;
}
void dfs(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++) {
if(used[i])continue;
used[i]=true;
path.add(nums[i]);
dfs(nums,used,path,res);
path.remove(path.size()-1);
used[i]=false;
}
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int>> res;
vector<int> path;
vector<char> used(nums.size(),0);
function<void()> dfs=[&]() {
if(path.size()==nums.size()) {
res.push_back(path);
return;
}
for(int i=0;i<(int)nums.size();i++) {
if(used[i])continue;
used[i]=1;
path.push_back(nums[i]);
dfs();
path.pop_back();
used[i]=0;
}
};
dfs();
return res;
}
};/**
* @param {number[]} nums
* @return {number[][]}
*/ var permute = function(nums) {
const res=[],used=new Array(nums.length).fill(false);
function dfs(path) {
if(path.length===nums.length) {
res.push(path.slice());
return;
}
for(let i=0;i<nums.length;i++) {
if(used[i])continue;
used[i]=true;
path.push(nums[i]);
dfs(path);
path.pop();
used[i]=false;
}
}
dfs([]);
return res;
};