leetcode 46 Permutations Python implement (backtracking)

 

Given a collection of distinct integers, return all possible permutations.

Example:

INPUT: [l, 2,3] 
the Output:
[
[l, 2,3],
[1,3,2],
[2,1, 3],
[2,3,1],
[3,1,2 ],
[3,2,1]
]

backtracking algorithm own one idea is as follows: the need to retain the use of digital, my_nums add and delete elements and other operations
. 1  class Solution:
 2      DEF permute (Self, the nums: List [int]) -> List [List [int]]:
 . 3          Results = []
 . 4          use_dict = dict.fromkeys (the nums, False) # initializing a dictionary, preservation of digital whether used 
. 5          DEF BackTrack (Results, my_nums, use_dict):
 . 6              iF len (my_nums) == len (the nums):
 . 7                  tmp_nums = copy.deepcopy (my_nums)
 . 8                  results.append (tmp_nums)
 . 9                  return 
10              
. 11              for X in nums:
 12                  IF  not use_dict[x]:
13                     use_dict[x] = True
14                     my_nums.append(x)  
15                     backtrack(results, my_nums, use_dict)
16                     my_nums.remove(x)  #remove操作耗费时间
17                     use_dict[x] = False
18         backtrack(results, [], use_dict)
19         return results

Overall program to spend more time, remove consume too much at the time, about over 24%

 Improved version:

 1 class Solution:
 2     def permute(self, nums: List[int]) -> List[List[int]]:
 3         results = []
 4         len_n = len(nums)
 5         def backtrack(my_nums, use_nums):
 6             if len(my_nums) == len_n:
 7                 results.append(my_nums)
 8                 return
 9             for i in range(len(use_nums)):
10                 x = my_nums.copy()
11                 x.append(use_nums[i])
12                 backtrack(x, use_nums[:i]+use_nums[i+1:])
13         backtrack([], nums)
14         return results

This will reduce the remaining available each recursive digital range, no maintenance use digital dict

my_nums every time a copy, so you do not need to remove the operation, the running time is shortened. 

Speed ​​of more than 98% Python

 

 

--- English leetcode station recently moved, so the title became English description

Guess you like

Origin www.cnblogs.com/watch-fly/p/leetcode_46_watchfly.html