码迷,mamicode.com
首页 > 编程语言 > 详细

[leetcode]Subsets II @ Python

时间:2014-05-29 19:10:53      阅读:278      评论:0      收藏:0      [点我收藏+]

标签:des   c   style   class   blog   code   

原题地址:https://oj.leetcode.com/problems/subsets-ii/

题意:

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],
  []
]

解题思路:和上一道题一样,求一个集合的所有子集。和上一道题不一样的一点是集合可能有重复元素。这道题同样使用dfs来解题,只是需要在dfs函数里加一个剪枝的条件,排除掉同样的子集。

代码:

bubuko.com,布布扣
class Solution:
    # @param num, a list of integer
    # @return a list of lists of integer
    def subsetsWithDup(self, S):
        def dfs(depth, start, valuelist):
            if valuelist not in res: res.append(valuelist)
            if depth == len(S): return
            for i in range(start, len(S)):
                dfs(depth+1, i+1, valuelist+[S[i]])
        S.sort()
        res = []
        dfs(0, 0, [])
        return res
bubuko.com,布布扣

 

[leetcode]Subsets II @ Python,布布扣,bubuko.com

[leetcode]Subsets II @ Python

标签:des   c   style   class   blog   code   

原文地址:http://www.cnblogs.com/zuoyuan/p/3758346.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!