【LeetCode with Python】 Subsets

博客域名: http://www.xnerv.wang
原题页面: https://oj.leetcode.com/problems/subsets/
题目类型:
难度评价:★
本文地址: http://blog.csdn.net/nerv3x3/article/details/36895699

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

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


普通的搜索算法即可解决,不过注意每个子序列都要以升序排列,所以从一开始就把输入的S排好序,一了百了,不知道是否还有其它更好的算法。


class Solution:

    def __init__(self):
        self.results = [ ]

    def doSubsets(self, S, cur_list, cur_index):
        if cur_index > len(S) - 1:
            self.results.append(cur_list)
            return
        cur_list0 = cur_list[:]
        cur_list1 = cur_list[:]
        cur_list1.append(S[cur_index])
        self.doSubsets(S, cur_list0, cur_index + 1)
        self.doSubsets(S, cur_list1, cur_index + 1)

    # @param S, a list of integer
    # @return a list of lists of integer
    def subsets(self, S):
        S.sort()
        self.doSubsets(S, [ ], 0)
        return self.results

你可能感兴趣的:(LeetCode,with,Python,LeetCode,with,Python,LeetCode,Python,LeetCode,with,Python)