×

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

Find Median of List in Python

The median is an enlightening measurement that is utilized as a proportion of the focal inclination of a circulation. It is equivalent to the centre worth of the conveyance. There...

3 minutes read.

Installing Packages in Python

It's critical to understand that the term "package" here refers to a collection of software that must be installed (i.e. as a synonym for a distribution). It has nothing to...

6 minutes read.

How to get current date in python?

How to get current date in python? In Python programming language, date and time are not just a data form, but it is possible to import a method called datetime to operate...

3 minutes read.

Dynamic Typing in Python

Many key factors for developing a great programming language include how it manages its memory space. This memory space largely depends on empty memory boxes called variables that one creates...

3 minutes read.

Python Empty Tuple

How to Create an Empty Tuple Tuple A tuple is a data structure used to store non-homogeneous data elements. These non-homogeneous data elements consist of integer data type, character data type, String...

3 minutes read.

Application to Search Installed Application using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

4 minutes read.

Python String split() method

The string.split() method in Python splits a string into a list and returns a list of the words in the string. If the parameter maxsplit is given, at most maxsplit splits are done. If maxsplit is...

2 minutes read.

Python set()

Python set() Class The set() class in Python returns a new set object, optionally with elements taken from iterable.  Syntax class set([iterable]) Parameter iterable : This parameter represents a sequence, collection or an iterator object Return This function returns a...

1 minute read.

Python String

Python String Python string is considered as the most popular data type present in Python language. In Python, string data type is the collection of characters, letters, white spaces etc. written...

31 minutes read.

Python Project Ideas Based On Django

Introduction If you have learned Python and you are an expert in Django, then your practical skills should be excellent in this field. If you want to check your practical skills,...

9 minutes read.

Parameter Passing in Python

In Python, when we characterize capabilities with default values for specific boundaries, it is said to have its contentions set as a possibility for the client. Clients can either pass their...

3 minutes read.

Python String islower() method

Python String islower() method The string.islower() method returns a boolean value true if all cased characters in the string are lowercase and for  any other value is returns false otherwise. Syntax string.islower() Parameter NA Return This...

1 minute read.

Python BS4 Code

Python BS4 Code The BS4 stands for BeautifulSoup version 4.x. The BeautifulSoup is a Python library which is used for pulling out data of the HTML & XML files using the...

14 minutes read.

Python str() function

Python str() function The str() function in Python converts the specified value into a string. Syntax class str(object='')           or class str(object=b'', encoding='utf-8', errors='strict') Parameter object:  This parameter represents any object to convert the given...

1 minute read.

Python all() Function

Python all() Function The all() function in Python returns a Boolean value ‘True’ if all the items in iterable are true or if the iterable object is empty, else it returns False. Syntax all(iterable) Parameter Iterable: An iterable object...

1 minute read.

ModuleNotFoundError No module named 'mysql' in Python

mysql module not found is an error that occurs in python. It appears like ModuleNotError: No module named 'mysql.' This error occurs when you forget to install a module called...

3 minutes read.

Python Continue Statement

In Python, loops automate and repeat processes in a cost-effective manner. However, there may be occasions when you wish to entirely exit the loop, skip an iteration, or ignore the...

3 minutes read.

Python Switch Case

What is a Switch Case Statement? In the programming languages, a switch statement is a logical loop or syntax that tests the variable's value and compares it with multiple cases. Once...

3 minutes read.

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.

Anaconda python 3.7 download for windows 10 64-bit

Before installing Anaconda, you need to first know what Anaconda actually is. Anaconda is an IDE (Integrated development environment) platform used to code and executes python programs. Anaconda works both online...

3 minutes read.