题目:
Given a collection of integers that might contain duplicates, S, 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 S = [1,2,2]
, a solution is:
[ [2], [1], [1,2,2], [2,2], [1,2], [] ]
代码:oj测试通过 Runtime: 78 ms
1 class Solution: 2 # @param num, a list of integer 3 # @return a list of lists of integer 4 def dfs(self, start, S, result, father_elements): 5 if father_elements in result: 6 return 7 result.append(father_elements) 8 for i in range(start, len(S)): 9 self.dfs(i+1, S, result, father_elements+[S[i]]) 10 11 def subsetsWithDup(self, S): 12 # none case 13 if S is None: 14 return [] 15 # deep first search 16 result = [] 17 first_depth = {} 18 self.dfs(0, sorted(S), result, []) 19 return result
思路:
大体思路跟Subsets差不多,详情见:
http://www.cnblogs.com/xbf9xbf/p/4253208.html
只需要每次向result中添加子集时注意判断一下这个子集是否已经存在。如果存在那么就直接返回,不做处理。