×

Permutations in Python

Recursion

Basic idea: for numbers of length N.

N-1 items are chosen at random between 0 and then generate permutations using the remaining N-1 elements in a recursive fashion. Once you've done that, add up your findings. The recursion code in Python will make this procedure easier to understand.

As an example, we may use swap(0-i),i in the range [0-1, 2...N-1] as an easy approach to pick up the values from num[0] to [N-1]. Below is an illustration of how this works:

OUTPUT

Permutations In Python

After a simple switch, the remaining values are no longer in the same order as they were before. To solve this problem, we may apply a better switching technique, as demonstrated in the updated image below:

OUTPUT

Permutations In Python

SYNTAX

/*

jimmy shen

02/20/2020

A code to implement the naive o(n^n) permutation algorithm.

runtime 12 ms

time complexity O(n!)

space complexity O(n) as we have temp

*/

class Solution {

public:

    vector<vector<int>> permute(vector<int>& nums) {

        vector<vector<int>> res;

        recursive_permute(nums, res, 0);

        return res;

    } 

    void recursive_permute(vector<int>&nums, vector<vector<int>> &res, int pos){

        // if we reach the size of nums, we are done.

        vector<int> temp = nums;

        if(pos == temp.size()-1){

            res.push_back(temp);

            return;

        }

        else{

            for(int i=pos; i<temp.size(); i++){

                swap(temp[pos], temp[i]);

                recursive_permute(temp, res, pos+1);

            }

        }

    }

};

Backtracking

Here's a quick rundown of how it works:

I in [0,1,2] is swapped with I in the first layer. To demonstrate the concept, I'll use the index parameter in the swap function. It's swapped in the programme (nums[0], nums[i])

For the second layer, we'll start at the second position and work our way up to the first.

When we get to the leaf node or the bottom case, we go back to the previous node and continue on.

It's DFS with a little bit of backtracking. If you've never heard of DFS or backtracking, now is the time to learn about it. First, do some research on Google to have a better understanding of those ideas.

runtime

Runtime: 8 ms, faster than 98.91% of C++ online submissions for Permutations.

Memory Usage: 9.2 MB, less than 95.52% of C++ online submissions for Permutations.

SYNTAX

/*

jimmy shen

02/20/2020

A code to implement the naive o(n^n) permutation algorithm.

runtime 12 ms

time complexity O(n!)

space complexity O(1)

*/

class Solution {

public:

    vector<vector<int>> permute(vector<int>& nums) {

        vector<vector<int>> res;

        dfs(nums, res, 0);

        return res;

    } 

    void dfs(vector<int>&nums, vector<vector<int>> &res, int pos){

        // if we reach the size of nums, we are done.

        if(pos >= nums.size()){

            res.push_back(nums);

            return;

        }

        else{

            for(int i=pos; i<nums.size(); i++){

                swap(nums[pos], nums[i]);

                dfs(nums, res, pos+1);

                //recover the nums to do backtracking

                swap(nums[pos], nums[i]);

            }

        }

    }

};

When the pos equals nums.size-1, we are done, and since there is only one element remaining, swap is unnecessary. Because of this, the code below is functional as well.

SYNTAX

class Solution {

public:

    vector<vector<int>> permute(vector<int>& nums) {

        vector<vector<int>> res;

        dfs(nums, res, 0);

        return res;

    } 

    void dfs(vector<int>&nums, vector<vector<int>> &res, int pos){

        // if we reach the size of nums, we are done.

        if(pos == nums.size()-1){

            res.push_back(nums);

            return;

        }

        else{

            for(int i=pos; i<nums.size(); i++){

                swap(nums[pos], nums[i]);

                dfs(nums, res, pos+1);

                //recover the nums to do backtracking

                swap(nums[pos], nums[i]);

            }

        }

    }

};

Backtracking differs from recursion in several ways.

They're really similar, in essence. That's because recursion employs a DFS strategy to address the issue. When we return to the parent node after DFS, we switch back to ensure that future investigation of other branches starts from a valid starting point when we go back to the parent node. As a result, when we approach the end of the DFS search, we'll need to do another swap.

We don't need to switch back for the recursion. However, we copy the initial num to temp and do the recursion actions on the basis of that.

Although it appears to be quite comparable, the memory complexity of recursion is O(n), where n is the size of nums. O is the name of the backtracking letter (1).

Runtime: 36 ms, faster than 83.58% of Python3 online submissions for Permutations.

Memory Usage: 13 MB, less than 96.43% of Python3 online submissions for Permutations.

SYNTAX

class Solution:

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

        res = []

        def dfs(pos):

            if pos==len(nums)-1:

                # using deep copy here to harvest the result

                res.append(nums[:])

            for i in range(pos, len(nums)):

                #swap

                nums[pos], nums[i] = nums[i], nums[pos]

                dfs(pos+1)

                nums[pos], nums[i] = nums[i], nums[pos]

        dfs(0)

        return res

Related Topics

Python Set clear() Method

Python Set clear() Method The set.clear() method removes all the elements from the set. Syntax set.clear() Parameter NA Return None Example 1 # Python program explaining # the set.clear() method # initializing the set fruits = {"watermelon", "banana", "apple"} # printing the set...

2 minutes read.

How to reverse a string in python

How to reverse a string in python A Brief About Strings- The String is a data type in Python that has a sequence of characters. This series of characters are represented in...

4 minutes read.

Python String splitlines() method

Python String splitlines() method The string.splitlines() method in Python splits the specified string and returns a list of the lines in the string, breaking at line boundaries.  Syntax splitlines([keepends]) Parameter keepends(optional): This parameter specifies if...

1 minute read.

How to build a Virtual Assistant Using Python

What is a virtual assistant? A virtual assistant is a new and very interesting concept in today’s world. When we hear the word “Virtual Assistant”, we can easily visualize “Jarvis or...

8 minutes read.

GUI Calendar using Tkinter in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

3 minutes read.

Python id() function

Python id() function The id() function in Python returns an id for the specified object where all the objects in has its own unique id. Syntax id(object) Parameter object: This parameter represents any object, String, Number, List,...

1 minute read.

Augmented reality in python

In this article, we shall learn about augmented reality in python. Augmented reality is a technology that captures the world around you and adds virtual content or objects on top of...

3 minutes read.

Best Python AI Projects

Artificial consciousness is advancing quickly, from Chabot's to self-driving vehicles. Because of the various advantages and development presented by AI, numerous enterprises have begun searching for AI-fueled applications. Thus, there...

7 minutes read.

Excel to CSV in Python

Define MS Excel Microsoft Excel is an application provided by the Microsoft corporation which allows us to build graphs to build tables, and it is also used for the macro programming...

4 minutes read.

Insertion Sort using Python

Insertion sort is a type of sorting technique that is used for sorting an array with random elements. Using sorting methods, any unsorted array can be sorted into ascending or...

3 minutes read.

Python Algorithms

A quote goes, "A goal without a plan is just a wish." To achieve anything in life, we can't simply go for it without making a plan and sticking to...

4 minutes read.

Python GUI Programming

GUI (Graphical User Interface) GUI is a graphics-based operating system that uses icons and menus to interact with the user. Python mostly works on CLI (Command Line Interface). Widgets Any user interface has...

4 minutes read.

Python Data Types

Python Data Types: The variable in Python is used to store values, and they can hold different values. Each variable in Python has its own data-type. Since Python is a...

13 minutes read.

Self in Python

 “self" is neither a keyword nor has a special meaning in Python, but it has a place and a job to do in Object-oriented programming. When we create a class...

6 minutes read.

Best books for NLP with Python

NLP NLP – Natural language processing Computers were created to make the life of mankind easier. But computers cannot understand human language. Instead, they interact with numbers to perform the tasks allotted...

12 minutes read.

Sort a dataframe based on a column in Python

Sorting the dataframe based on a column requires pandas which is An open-source library called Python Pandas is described as offering high-performance data processing in Python. For both professionals and...

4 minutes read.

Python Argmin

Introduction The argmin function is defined as numpy.argmin(). This function returns the index of the minimum value or element from a Numpy array in a specific axis. An array is taken...

3 minutes read.

Number Pattern Programs in Python

Learning Python is very easy, and it understands in better way compared to other programming languages. One of the many reasons why it has emerged as the most widely used...

4 minutes read.

Merge Sort using Python

Merge Sort is a technique that is used for sorting elements in an array using a special method known as divide and conquer. It is the best example of the...

5 minutes read.

Convert String to Binary in Python

String to binary The strings can be defined as the array of Unicode code characters. Binary Binary is defined as the number system which consists two symbols 0 and 101. It is base-2...

2 minutes read.