LeetCode 46. Permutations

🧩 Problem Description

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


💬 Example

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

💡 Approach: Backtracking

We use backtracking to generate all permutations by swapping elements or by building a temporary path with used flags.

🔢 Java Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import java.util.*;

class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
backtrack(nums, new ArrayList<>(), new boolean[nums.length], result);
return result;
}

private void backtrack(int[] nums, List<Integer> path, boolean[] used, List<List<Integer>> result) {
if (path.size() == nums.length) {
result.add(new ArrayList<>(path));
return;
}
for (int i = 0; i < nums.length; i++) {
if (used[i]) continue;
used[i] = true;
path.add(nums[i]);
backtrack(nums, path, used, result);
path.remove(path.size() - 1);
used[i] = false;
}
}
}

⏱ Complexity Analysis

  • Time: O(n × n!) → each permutation takes O(n) to build, total n! permutations
  • Space: O(n) recursion depth + O(n) used flags

✍️ Summary

  • Classic backtracking problem.
  • Generates all n! permutations.
  • Useful in problems involving ordering, scheduling, or searching solution spaces.

Related problems:

  • lc-47 — Permutations II (with duplicates)
  • lc-77 — Combinations
  • lc-78 — Subsets
  • lc-90 — Subsets II