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 | Input: nums = [1,2,3] |
💡 Approach: Backtracking
We use backtracking to generate all permutations by swapping elements or by building a temporary path with used flags.
🔢 Java Code
1 | import java.util.*; |
⏱ 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
— Combinationslc-78
— Subsetslc-90
— Subsets II