Recursion & Backtracking · Pattern 4 of 9
Permutations: every order of the items
Fill position by position with an item not used yet. Either swap candidates into place or keep a used array; for duplicates, sort and only use the first unused copy of each value.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- Every ordering or arrangement of the items
- Each item must be used exactly once
- Assign distinct values (digits, seats) to distinct things
The template
// swap trick: positions 0..i-1 are fixed, try every item from i.. in position i
List<List<Integer>> permute(int[] a) {
List<List<Integer>> out = new ArrayList<>();
swapGo(a, 0, out);
return out;
}
void swapGo(int[] a, int i, List<List<Integer>> out) {
if (i == a.length) {
List<Integer> p = new ArrayList<>();
for (int x : a) p.add(x);
out.add(p);
return;
}
for (int j = i; j < a.length; j++) {
swap(a, i, j);
swapGo(a, i + 1, out);
swap(a, i, j); // swap back
}
}
void swap(int[] a, int i, int j) { int t = a[i]; a[i] = a[j]; a[j] = t; }
// with duplicates: sort, and use a value only if its earlier copy is already in the path
List<List<Integer>> permuteUnique(int[] a) {
Arrays.sort(a);
List<List<Integer>> out = new ArrayList<>();
usedGo(a, new boolean[a.length], new ArrayList<>(), out);
return out;
}
void usedGo(int[] a, boolean[] used, List<Integer> path, List<List<Integer>> out) {
if (path.size() == a.length) { out.add(new ArrayList<>(path)); return; }
for (int i = 0; i < a.length; i++) {
if (used[i] || (i > 0 && a[i] == a[i - 1] && !used[i - 1])) continue;
used[i] = true; path.add(a[i]);
usedGo(a, used, path, out);
path.remove(path.size() - 1); used[i] = false;
}
} def permute(a): # swap trick
a, out = a[:], []
def go(i):
if i == len(a):
out.append(a[:])
return
for j in range(i, len(a)):
a[i], a[j] = a[j], a[i]
go(i + 1)
a[i], a[j] = a[j], a[i] # swap back
go(0)
return out
def permute_unique(a): # sort; use a value only after its earlier copy
a, out, path = sorted(a), [], []
used = [False] * len(a)
def go():
if len(path) == len(a):
out.append(path[:])
return
for i in range(len(a)):
if used[i] or (i > 0 and a[i] == a[i - 1] and not used[i - 1]):
continue
used[i] = True; path.append(a[i])
go()
path.pop(); used[i] = False
go()
return out // swap trick: positions 0..i-1 are fixed, try every item from i.. in position i
void swapGo(vector<int>& a, int i, vector<vector<int>>& out) {
if (i == (int)a.size()) { out.push_back(a); return; }
for (int j = i; j < (int)a.size(); j++) {
swap(a[i], a[j]);
swapGo(a, i + 1, out);
swap(a[i], a[j]); // swap back
}
}
vector<vector<int>> permute(vector<int>& a) {
vector<vector<int>> out;
swapGo(a, 0, out);
return out;
}
// with duplicates: sort, and use a value only if its earlier copy is already in the path
void usedGo(vector<int>& a, vector<bool>& used, vector<int>& path, vector<vector<int>>& out) {
if (path.size() == a.size()) { out.push_back(path); return; }
for (int i = 0; i < (int)a.size(); i++) {
if (used[i] || (i > 0 && a[i] == a[i - 1] && !used[i - 1])) continue;
used[i] = true; path.push_back(a[i]);
usedGo(a, used, path, out);
path.pop_back(); used[i] = false;
}
}
vector<vector<int>> permuteUnique(vector<int>& a) {
sort(a.begin(), a.end());
vector<vector<int>> out; vector<int> path; vector<bool> used(a.size());
usedGo(a, used, path, out);
return out;
} // swap trick: positions 0..i-1 are fixed, try every item from i.. in position i
function permute(a) {
a = [...a];
const out = [];
function go(i) {
if (i === a.length) { out.push([...a]); return; }
for (let j = i; j < a.length; j++) {
[a[i], a[j]] = [a[j], a[i]];
go(i + 1);
[a[i], a[j]] = [a[j], a[i]]; // swap back
}
}
go(0);
return out;
}
// with duplicates: sort, and use a value only if its earlier copy is already in the path
function permuteUnique(a) {
a = [...a].sort((x, y) => x - y);
const out = [], path = [], used = new Array(a.length).fill(false);
function go() {
if (path.length === a.length) { out.push([...path]); return; }
for (let i = 0; i < a.length; i++) {
if (used[i] || (i > 0 && a[i] === a[i - 1] && !used[i - 1])) continue;
used[i] = true; path.push(a[i]);
go();
path.pop(); used[i] = false;
}
}
go();
return out;
} The variations
-
1Every order of distinct items
Position by position, try each item that is not used yet. A
usedarray (or the swap trick) makes "not used yet" an O(1) check. -
2Permutations with duplicates
Sort, then treat equal values as a queue: a copy may be used only if the copy before it is already in the path. Each distinct order is then built once.
-
3Assign distinct values under a constraint
Letters get distinct digits, which is a permutation of digits over letters. Fill column by column from the right, carry the sum, and prune a branch as soon as a column cannot balance.
Mistakes to avoid
- Forgetting to swap back, so the array is scrambled for the next branch.
- Using the swap trick with duplicates: swapping scrambles the sorted order, so the "skip equal neighbours" rule no longer works. Use the used array instead.
- Starting the loop at a start index (as in subsets): permutations try every unused item at every position.
Lesson done
Next: Grid backtracking: paths and boards →Mark it done once you can write the template from memory and you have solved the worked examples yourself.