Permutations in Python

PythonServer Side ProgrammingProgramming

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)


Let us see the following implementation to get a better understanding −

 Live Demo

class Solution(object):
   def permute(self, nums):
      result = []
      return result
   def permute_util(self,given_list,start,curr,result):
      if start > len(given_list)-1:
      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)
         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()




Updated on 27-Apr-2020 13:18:41