2014 年 7 月 4 日 16:11:00 約 1 分鐘 116 字 174 個單字
題目
原題頁面:https://leetcode.com/problems/subsets-ii/
題目型別:Array, Backtracking
難度評價:Medium
Given a collection of integers that might contain duplicates,nums , return all possible subsets.
Note:
Elements in a subset must be in non-descending order.
The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,2], a solution is:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
分析
與Subsets差不多,先對輸入的列表S排序,唯一需要改動的是隻是需要在每次遞迴的時候記憶前一個字元,從而避免一種情況:相等的字元,如果前一個沒有才採納,則後面的字元則也不能被採納,通過這種方式可以避免產生重複的子序列。
程式碼
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 class Solution : def __init__ (self ): self .results = [ ] def doSubsets (self, S, cur_list, cur_index, last_ch, add_last_ch ): if cur_index > len (S) - 1 : self .results.append(cur_list) return cur_list0 = cur_list[:] self .doSubsets(S, cur_list0, cur_index + 1 , S[cur_index], False ) if not last_ch == S[cur_index] or add_last_ch: cur_list1 = cur_list[:] cur_list1.append(S[cur_index]) self .doSubsets(S, cur_list1, cur_index + 1 , S[cur_index], True ) def subsetsWithDup (self, S ): self .results = [ ] S.sort() self .doSubsets(S, [ ], 0 , "" , False ) return self .results
本文地址:https://xnerv.wang/zh-tw/leetcode-subsets-ii/