您的位置:首页 > 编程语言 > Python开发

leetcode 【 Subsets II 】python 实现

2015-01-27 19:48 281 查看
题目

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

class Solution:
# @param num, a list of integer
# @return a list of lists of integer
def dfs(self, start, S, result, father_elements):
if father_elements in result:
return
result.append(father_elements)
for i in range(start, len(S)):
self.dfs(i+1, S, result, father_elements+[S[i]])

def subsetsWithDup(self, S):
# none case
if S is None:
return []
# deep first search
result = []
first_depth = {}
self.dfs(0, sorted(S), result, [])
return result


思路

大体思路跟Subsets差不多,详情见:

/article/5261266.html

只需要每次向result中添加子集时注意判断一下这个子集是否已经存在。如果存在那么就直接返回,不做处理。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: