Lintcode 18. Subsets II (Medium) (Python)

Subsets II

Description:

Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).

Example
Input: [1,2,2]
Output:

[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
Challenge
Can you do it in both recursively and iteratively?

Notice
Each element in a subset must be in non-descending order.
The ordering between two subsets is free.
The solution set must not contain duplicate subsets.

Code:

class Solution:
    """
    @param nums: A set of numbers.
    @return: A list of lists. All valid subsets.
    """
    def subsetsWithDup(self, nums):
        # write your code here
        def travel(num, dep, cur):
            print("num is", num, "dep is", dep, "cur is", cur)
            if cur not in res:
                print("append", cur)
                res.append(cur)
            if dep==len(nums):
                print("equal")
                return
            for i in range(len(num)):
                print("num=", num, "cur+[nums[i]]=", cur+[nums[i]])
                travel(num[i+1:], dep+1, cur+[num[i]])
        nums.sort()
        res = []
        travel(nums, 0, [])
        return res
阅读更多
文章标签: Lintcode Python
个人分类: Lintcode刷题
想对作者说点什么? 我来说一句
相关热词

没有更多推荐了,返回首页

关闭
关闭
关闭