CodingNodes / Backtracking / Permutations System design Space play · ←→ step · R restart

Problem

You are given an array nums of different integers. Return every way to arrange all of its numbers in a row. Each arrangement uses every number exactly once.

The arrangements may be returned in any order, but the order of the numbers inside each arrangement matters.

Constraints

  • 1 ≤ nums.length ≤ 6
  • -10 ≤ nums[i] ≤ 10
  • All numbers in nums are different

Examples: pick one to animate

Solutions

TimeO(n · n!) SpaceO(n)

Time: There are n! arrangements and each is copied into the answer in O(n). The tree has about e · n! nodes, each with an O(n) loop, which is still O(n · n!) overall.

Space: Besides the output, the path, the used array and the recursion depth are each at most n.

Fill the path left to right. At every step try each number that is not marked used: mark it, add it, recurse, then undo both. When the path has n numbers, save a copy.