16. 帶重複元素的排列
阿新 • • 發佈:2020-08-27
16.帶重複元素的排列
中文English給出一個具有重複數字的列表,找出列表所有不同的排列。
樣例
樣例 1:
輸入:[1,1]
輸出:
[
[1,1]
]
樣例 2:
輸入:[1,2,2]
輸出:
[
[1,2,2],
[2,1,2],
[2,2,1]
]
挑戰
使用遞迴和非遞迴分別完成該題。
DFS寫法
class Solution: """ @param: : A list of integers @return: A list of unique permutations """ def permuteUnique(self, nums): # write your code here #for迴圈內嵌dfs寫法if not nums: return [[]] results = [] visted = {} self.dfs(results, nums, [], 0, visted) return results def dfs(self, results, nums, array, index, visted): #遞迴的出口 if (len(array) == len(nums)): if (array not in results): results.append(list(array))return #遞迴的拆解 for i in range(len(nums)): if (i not in visted): visted[i] = True array.append(nums[i]) self.dfs(results, nums, array, index + 1, visted) array.pop() visted.pop(i)