Knowee
Questions
Features
Study Tools

Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.

Question

Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.

🧐 Not the exact question you are looking for?Go ask a question

Solution

Sure, here is a Python solution using recursion and backtracking:

def permute(nums):
    def backtrack(first = 0):
        # if all integers are used up
        if first == n:  
            output.append(nums[:])
        for i in range(first, n):
            # place i-th integer first 
            # in the current permutation
            nums[first], nums[i] = nums[i], nums[first]
            # use next integers to complete the permutations
            backtrack(first + 1)
            # backtrack
            nums[first], nums[i] = nums[i], nums[first]
            
    n = len(nums)
    output = []
    backtrack()
    return output

Here's how it works:

  1. If all integers are used up, add the permutation to the output.
  2. Iterate over the integers from first to the end of array.
  3. Place the integer at index first that we're iterating on at the beginning of the permutation, i.e. swap(nums[first], nums[i]).
  4. Proceed to create all permutations which starts from first and keeps first+1 in the remaining part.
  5. Now we have to backtrack, so we swap the numbers back to restore the original array. We do this because we want to try a different possibility for the number at the first index.
  6. Repeat the process until we have found all permutations.

This problem has been solved

Similar Questions

Given a list of integers, count and return the number of times each value appears as an array of integers.

How many permutations exist of the word "PASCALS"? Leave your answer in factorial form.

Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.

Write a class to sort the given set of integers in descending order. Include a try block tolocate the array index out of bounds exception and catch it.

Print Array Elements (Recursive): Write a function that recursively prints the elements of an array in order.

1/1

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.