oneby7

Recursion and Backtracking Generating every choice

327. Permutations II

Medium

You are given an array of integers nums, and the same value can appear in it more than once. Return every distinct arrangement of its values.

An arrangement is a list that holds every element of nums exactly once, in some order. Two arrangements are the same when every position holds the same value in both. So swapping two equal values gives the same arrangement, and it is returned once. nums itself is one of the arrangements.

The arrangements can come back in any order. The order of the values inside each arrangement is what makes it that arrangement, so that order matters. The examples sort the arrangements by their first value, then by their second value, and so on.

Example 1

Input: nums = [2, 0, 2, 0]

Output: [[0,0,2,2], [0,2,0,2], [0,2,2,0], [2,0,0,2], [2,0,2,0], [2,2,0,0]]

Explanation: The four elements can be put in 24 orders. Swapping the two 2s, or the two 0s, gives the same list, so each list comes up four times. That leaves 6 distinct arrangements, and [2,0,2,0] itself is one of them.

Example 2

Input: nums = [0, -4, 0, 0]

Output: [[-4,0,0,0],[0,-4,0,0],[0,0,-4,0],[0,0,0,-4]]

Explanation: The three 0s are interchangeable, so an arrangement is decided by where −4 goes. It can take any of the four positions.

Example 3

Input: nums = [-1000000000, 0, 1000000000]

Output: [[-1000000000,0,1000000000], [-1000000000,1000000000,0], [0,-1000000000,1000000000], [0,1000000000,-1000000000], [1000000000,-1000000000,0], [1000000000,0,-1000000000]]

Explanation: No value repeats, so all 3 × 2 = 6 orders are different arrangements. The values can be as large or as small as 109 and −109.

Check your understanding

Work out the answer for this input before you write any code.

nums = [6, 6, 1]

Constraints

  • 1 ≤ nums.length ≤ 8
  • -109 ≤ nums[i] ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.