Permutations

Medium
backtracking

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

A permutation is an arrangement of all elements where order matters. For n distinct elements, there are n! (n factorial) possible permutations.

Unlike subsets where we choose to include/exclude elements, in permutations we must use ALL elements exactly once, just in different orders. At each position in the permutation, we can place any element that hasn't been used yet.

The backtracking approach: at each step, try placing each unused element, recurse, then backtrack by unmarking the element as used.

Example 1

Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
Explanation: There are 3! = 6 permutations. Each uses all three numbers exactly once.

Example 2

Input: nums = [0,1]
Output: [[0,1],[1,0]]
Explanation: Two elements produce 2! = 2 permutations.

Example 3

Input: nums = [1]
Output: [[1]]
Explanation: Single element has only one permutation - itself.

Constraints

  • 1 <= nums.length <= 6
  • -10 <= nums[i] <= 10
  • All the integers of nums are unique
Show Hints (4)
Hint 1: How is this different from subsets? Here you must use ALL elements.
Hint 2: At each position, which elements can you place?
Hint 3: You need to track which elements have already been used in the current permutation.
Hint 4: After placing an element and exploring, how do you "unplace" it to try other options?
Loading editor...

Test Results

Click "Run" to execute your code against test cases

AI Tutor

Socratic guidance - I'll ask questions, not give answers

AI Tutor
Hello! I'm your AI tutor, here to guide you through this problem using the Socratic method. I won't give you direct answers, but I'll ask questions and provide hints to help you discover the solution yourself. What's your first instinct when you look at this problem? What approach comes to mind?