約 1 分鐘62 字153 個單字
題目
原題頁面:https://leetcode.com/problems/permutations-ii/
題目型別:Backtracking
難度評價:Medium
類似題目:(M) Next Permutation, (M) Permutations, (M) Palindrome Permutation II
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
For example,
[1,1,2] have the following unique permutations:
[1,1,2], [1,2,1], and [2,1,1].
分析
與Permutations在處理上的唯一區別是,對於重複元素,不去嘗試調換,而是直接skip,避免出現重複的排列。
程式碼
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| class Solution: def doPermuteUnique(self, num_list): if 1 == len(num_list): return [ num_list ] res_list = [ ] for i in range(0, len(num_list)): if i > 0 and num_list[0] == num_list[i]: continue num_list[0], num_list[i] = num_list[i], num_list[0] sub_res_list = self.doPermuteUnique(num_list[1:]) list_head = [ num_list[0] ] new_list = [ list_head + list for list in sub_res_list] res_list.extend(new_list) return res_list
def permuteUnique(self, num): num.sort() return self.doPermuteUnique(num)
|
本文地址:https://xnerv.wang/zh-tw/leetcode-permutations-ii/