← All Exercises

Generate All Permutations with Backtracking

intermediatejavascript~25min

Background

Permutation generation underlies scheduling search, anagram solving, and brute-force verification in testing tools.

Problem

Given an array of distinct integers, return all possible permutations. The permutations must be ordered lexicographically when the input is sorted.

Input

An array nums of up to 8 distinct integers, given in ascending order.

Output

An array of permutations, each a copy of nums reordered, in lexicographic order.

Sample tests

Sample 1

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

Sample 2

Input: nums = [0,1]
Expected: [[0,1],[1,0]]

Sample 3

Input: nums = [7]
Expected: [[7]]

Your solution

Learning objective

Apply the choose, explore, un-choose backtracking template and analyze factorial output size.