

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Permutations in Python
Suppose we have a collection of distinct integers; we have to find all possible permutations. So if the array is like [2,1,3], then the result will be [[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]]
To solve this, we will follow these steps −
- We will use the recursive approach, this will make the list, start, curr and res
- if start > length of list – 1, then add curr into the res, and return
- for i in range start to length of given list – 1
- swap the elements of list present at index start and (start + (i – start))
- permutation(list, start + 1, curr + [list[start]], res)
- swap the elements of list present at index start and (start + (i – start))
- initially call the permutation(arr, 0, [], res)
Example(Python)
Let us see the following implementation to get a better understanding −
class Solution(object): def permute(self, nums): result = [] self.permute_util(nums,0,[],result) return result def permute_util(self,given_list,start,curr,result): if start > len(given_list)-1: #print(curr) result.append(curr) return for i in range(start,len(given_list)): self.swap(given_list,start,start+(i-start)) self.permute_util(given_list,start+1,curr+[given_list[start]],result) #print(given_list) self.swap(given_list, start, start + (i - start)) def swap(self,nums,index1,index2): temp = nums[index1] nums[index1] = nums[index2] nums[index2] = temp ob1 = Solution() print(ob1.permute([1,2,3,4]))
Input
[1,2,3,4]
Output
[[1,2,3,4],[1,2,4,3],[1,3,2,4],[1,3,4,2],[1,4,3,2],[1,4,2,3],[2,1,3,4],[2,1,4,3],[2,3,1,4],[2,3,4,1],[2,4,3,1],[2,4,1,3],[3,2,1,4],[3,2,4,1],[3,1,2,4],[3,1,4,2],[3,4,1,2],[3,4,2,1],[4,2,3,1],[4,2,1,3],[4,3,2,1],[4,3,1,2],[4,1,3,2],[4,1,2,3]]
- Related Questions & Answers
- All possible permutations of N lists in Python
- Permutations II in C++
- How to generate all permutations of a list in Python?
- Python - Generate all possible permutations of words in a Sentence
- Print first n distinct permutations of string using itertools in Python
- Calculating Josephus Permutations efficiently in JavaScript
- Python Program to print all permutations of a given string
- Missing Permutations in a list in C++
- How to find all possible permutations of a given string in Python?
- Valid Permutations for DI Sequence in C++
- Creating permutations by changing case in JavaScript
- Python program to get all permutations of size r of a string
- Print all permutations of a string in Java
- Generating all possible permutations of array in JavaScript
- How can SciPy be used to calculate the permutations and combination values in Python?
Advertisements