×

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 String swapcase() method

Python String swapcase() method The string.swapcase() method in Python returns a copy of the string with uppercase characters converted to lowercase and vice versa. Syntax string.swapcase() Parameter NA Return This method returns a copy of the string...

1 minute read.

Kite Python

Kite in Python: The Kite is a package provided by the python programming language; it works with the help of artificial intelligence and helps us write code inside the visual studio....

3 minutes read.

Python for Loop Increment

Introduction In general, loops are employed for sequential traversal. It belongs to the definite iteration category. Definite iterations imply that the number of iterations is explicitly set in advance.  In this article,...

4 minutes read.

Flutter with tensor flow in python

Python : Python is an object oriented programming language which is highly interpreted and is highly interactive. Python was created by Guido van Rossum in the year 1985 – 1990 .The...

3 minutes read.

How to Configure Python Interpreter in Eclipse

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Curdir Python

Python Programming Language Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a...

3 minutes read.

_name_ in Python

Introduction: The code at level 0 indentation is to be performed when the command to run a Python program is supplied to the interpreter because Python does not have a main() function...

4 minutes read.

How to Convert A List into String In Python?

How to Convert A List into String In Python? List is a data structure in Python that can hold values of different data types. The values are enclosed in square brackets...

3 minutes read.

How to Write a Configuration file in Python

This article will discuss How to write a configuration file in python, why we need config files in Python, the format of the configuration file, file extensions, and how to...

11 minutes read.

How to find square root in python

How to find Square Root of a number In Python Python makes a lot of tasks easier by using different functions, modules, and libraires. There is an inbuilt function in Python...

6 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.

Python vs HTML

Python and HTML are not comparable since they are two separate categories of programming languages. Building the structures and layouts of a web page or app requires the usage of HTML,...

8 minutes read.

Returning Multiple Values in Python

Python is considered a general-purpose programming language; it is a high-level programming language that is not much difficult and easier to learn. It is rich in libraries that can be...

3 minutes read.

Compound Interest GUI Calculator using Tkinter in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

6 minutes read.

Python Stack

Python Stack: The work Stack is defined as arranging a pile of objects or items on top of another. It is the same method of allocating memory in the stack...

10 minutes read.

Sublime Python

SUBLIME: A compact, cross-platform code editor called Sublime Text 3 (ST3) is well-known for its quickness, usability, and robust community support. Although it's a fantastic editor out of the box, its...

6 minutes read.

Is Python Case Sensitive

Case sensitivity is the mode of dealing with the written alphabet. The cases of the alphabet are examined and based on these words are being treated. The uppercase and lowercase...

3 minutes read.

How to Define a Function in Python?

What is a Function? In programming, a piece of code that executes a specific task or a group of related operations is known as a function. What does Python Functions Do? If you...

6 minutes read.

Check whether dir is empty or not in python

Python: Check if a directory is empty In this tutorial, we will study how to check whether the director (dir) is empty or not in the python programming language. First of...

3 minutes read.

Python Control Statements

Control statements are under the roof topic of loops and loops in python are defined as iteratively and repeatedly working on source code. Loop control statements are defined as they...

3 minutes read.