Instagram
youtube
Facebook
Twitter

Permutations Leetcode Solution

In this tutorial, we will solve a leetcode problem Permutations in python.

Task:

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

Example 1:

Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]


Example 2:

Input: nums = [0,1]
Output: [[0,1],[1,0]]


Example 3:

Input: nums = [1]
Output: [[1]]


Solution:

class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:

        if len(nums) == 1:
            return [nums]
        
        lst = []
        
        for j in range(len(nums)):
            
            k = nums[j]
            p = nums[:j] + nums[j+1:]

            for i in self.permute(p):
                lst.append([k] + i)
                
        return lst

Steps:

step1: We will solve this problem recursively, Firstly, we will add base case i.e. if the length of nums is 1 then we return nums as a sublist.

step2: make an empty list, then loop for in a range of length of nums.

step3; then we set a variable k to the nums[j] and declare a list p which is equal to nums except for k.

step4: then we call the permute function recursively on p as an array and append the k + index i to the lst, after the loop we return the lst.