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.
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:
- If all integers are used up, add the permutation to the output.
- Iterate over the integers from
first
to the end of array. - Place the integer at index
first
that we're iterating on at the beginning of the permutation, i.e. swap(nums[first], nums[i]). - Proceed to create all permutations which starts from
first
and keepsfirst+1
in the remaining part. - 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. - Repeat the process until we have found all permutations.
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.
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.