AceYourInterviews
Checking sign-in…

120. Permutations

IntermediatePosition ownership for complete ordered arrangements

Arrange every supplied value in every possible order. Each result must contain all input values exactly once.

Unlike subsets, permutations always use the full input. Two rows with different orders are different answers, and the empty-input convention is stated below.

Example 1

Input

[3,1,2]

Output

[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

Explanation: The private sorted copy determines traversal order; nums remains [3,1,2].

Example 2

Input

[]

Output

[[]]

Explanation: There is exactly one way to arrange no values.

Example 3

Input

[7]

Output

[[7]]

Explanation: A full-length leaf emits once.

Constraints

  • 0 <= nums.length <= 9
  • -231 <= nums[i] <= 231 - 1
  • All input values are distinct.
Hints
Hint 1

Each next position can use any input occurrence absent from the active path.

Hint 2

Keep a used array whose true positions match the path exactly.

Hint 3

At full length copy the path; otherwise choose, mark, recurse, and undo both changes.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

Undo makes an earlier value available to a later sibling

[2,1]
[[1,2],[2,1]]