Subsets

来源:互联网 发布:ftp阿里云服务器配置 编辑:程序博客网 时间:2024/06/05 04:15

题目:

Given a set of distinct integers, nums, 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 nums = [1,2,3], a solution is:


[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]


解题思路:

在前已有所述,在此不再赘述。参考http://blog.csdn.net/u010455041/article/details/44560917

class Solution:
    # @param {integer[]} nums
    # @return {integer[][]}
    def subsets(self, nums):
        def convert_to_binary(n,limit):
            bi = []
            while (n>0):
                bi.append(n%2)
                n = n / 2
            if len(bi)<limit:
                bi += [0 for i in range(limit-len(bi))]
            return bi
        
        res = [[]]
        length = len(nums)
        power = pow(2,length)
        for i in range(1,power):
            bi = convert_to_binary(i,length)
            tmp = []
            for index,x in enumerate(bi):
                if x==1:
                    tmp.append(nums[index])
            tmp.sort()
            res.append(tmp)
        return res


0 0
原创粉丝点击