class Solution:
"""
@param: nums: A list of integers.
@return: A list of permutations.
"""def permute(self, nums):
# write your code here#递归版本
results = []
self.dfs(results, [], nums)
return results
#递归的定义,传入几个参数def dfs(self, results, array, nums):
#递归的出口,如果是长度已经符合的话,则返回if (len(array) == len(nums)):
results.append(list(array))
return#递归的拆解for num in nums:
if num notin array:
array.append(num)
#一直会回来在重新循环判断,是否符合要求 self.dfs(results, array, nums)
#返回完毕之后,开始移除 array.pop()
全排列II
如果是存在重复的元素,也是每个元素只能使用一次的话
DFS + Visit(已经访问过的记录,index) + 回溯
写法1:
class Solution:
"""
@param: nums: A list of integers.
@return: A list of permutations.
"""def permute(self, nums):
# write your code here#递归版本
results = []
visits = {}
self.dfs(results, [], nums, visits)
return results
#递归的定义,传入几个参数def dfs(self, results, array, nums, visits):
#递归的出口,如果是长度已经符合的话,则返回if (len(array) == len(nums)):
results.append(list(array))
return#递归的拆解for i in range(len(nums)):
#如果是存在重复的数的话,如果是之前已经访问过,则记录下来,否则则可以进行插入if i notin visits:
array.append(nums[i])
visits[i] = True
#一直会回来在重新循环判断,是否符合要求,下一次走就会自动从下一个开始走 self.dfs(results, array, nums, visits)
#返回完毕之后,开始移除 array.pop() #开始往回移除的时候,visits也开始删除访问记录
visits.pop(i)
写法2:
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
def backtrack(res, path, record):
if (len(path) == len(nums)):
if path not in res:
res.append(path)
returnfor i in range(len(nums)):
if (i in record):
continue
backtrack(res, path + [nums[i]], record + [i])
l = len(nums)
res = []
path = []
record = []
backtrack(res, path, record)
return res