原題
給定一個(gè)可能具有重復(fù)數(shù)字的列表罢低,返回其所有可能的子集
如果S = [1,2,2]判帮,一個(gè)可能的答案為:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
子集中的每個(gè)元素都是非降序的
兩個(gè)子集間的順序是無(wú)關(guān)緊要的
解集中不能包含重復(fù)子集
解題思路
- 如題,我們只關(guān)心有幾個(gè)2,不關(guān)心順序,換句話說(shuō)[1, 2(1), 2(2)]和[1, 2(2), 2(1)]是一樣的
- 對(duì)于每次層袋倔,如果current == previous則跳過(guò)
if i != pos and List[i] == List[i - 1]:
continue
完整代碼
class Solution(object):
def subsetsWithDup(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
if not nums:
return []
else:
result.append([])
self.dfs(sorted(nums), 0, [], result)
return result
def dfs(self, List, pos, path, result):
for i in range(pos, len(List)):
if i != pos and List[i] == List[i - 1]:
continue
else:
result.append(path + [List[i]])
self.dfs(List, i + 1, path + [List[i]], result)