Permutations

Medium· backtracking· permutations

Problem

Given an array of distinct integers, return every ordering of its elements. Each permutation uses every element exactly once, and the list of permutations may be in any order.

Examples

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

Constraints

  • • 1 <= nums.length <= 6
  • • All elements are distinct

Hints & approach

Hint 1

Fill positions left to right; each position can take any element not yet used.

Hint 2

Track which elements are already in the current path with a boolean array.

Hint 3

Alternatively, swap each candidate into the current position and recurse on the rest.

Approachtry the hints first

Keep a current path and a used[] flag per element. At each level loop over all elements; skip used ones, otherwise mark it, append it, recurse, then unmark and remove it. When the path length equals n, save a copy. The in-place variant swaps nums[i] with nums[start] for each i >= start, recurses on start + 1, and swaps back, which avoids the extra flag array.

Time O(n * n!) · Space O(n) recursion, excluding output

Output
Call your solution with a test case and Run. For the full judge, submit on LeetCode.