☰ All problems

Permutations

A relay coach wants to try out every possible running order for the team before race day. Each runner is identified by a distinct integer bib number in nums.

Return all permutations of nums: every ordering of all the runners, each listed exactly once. The orderings can be returned in any order.

Example 1
Input: nums = [4,7,2]
Output: [[4,7,2],[4,2,7],[7,4,2],[7,2,4],[2,4,7],[2,7,4]]

Explanation: Three runners can line up in 3! = 6 different orders.

Example 2
Input: nums = [-3,5]
Output: [[-3,5],[5,-3]]

Explanation: Either runner can go first.

Constraints

  • nums holds between 1 and 6 bib numbers.
  • The bib numbers are distinct integers from -10 to 10.

Follow-up: If two runners could share a bib number, how would you avoid listing the same order twice?

💡 Hint 1

There are n! permutations. Build them one position at a time.

💡 Hint 2

Backtracking: keep the current partial permutation and a used flag per element. At each step, try every unused element, recurse, then undo the choice.

💡 Hint 3

When the partial permutation has length n, add a copy of it to the answer.

/**
 * @param {number[]} nums
 * @return {number[][]}
 */
function permute(nums) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc