Advertisement
aero2146

Permutations

Apr 10th, 2020
205
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.75 KB | None | 0 0
  1. class Solution:
  2.     def permute(self, nums):
  3.         """
  4.        :type nums: List[int]
  5.        :rtype: List[List[int]]
  6.        """
  7.         def backtrack(first = 0):
  8.             # if all integers are used up
  9.             if first == n:  
  10.                 output.append(nums[:])
  11.             for i in range(first, n):
  12.                 # place i-th integer first
  13.                 # in the current permutation
  14.                 nums[first], nums[i] = nums[i], nums[first]
  15.                 # use next integers to complete the permutations
  16.                 backtrack(first + 1)
  17.                 # backtrack
  18.                 nums[first], nums[i] = nums[i], nums[first]
  19.        
  20.         n = len(nums)
  21.         output = []
  22.         backtrack()
  23.         return output
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement