简繁EN

LeetCodeNo. 081

[LeetCode with Python] 78. Subsets

Contents

Problem

Problem page: https://leetcode.com/problems/subsets/
Topics: Array, Backtracking, Bit Manipulation
Difficulty: Medium

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

Analysis

A simple search algorithm will do, but each subsequence has to be in ascending order, so I sort the input S right at the start and get that out of the way. I wonder if there's a better algorithm.
Going down and coming back are the two keys to recursive backtracking. On the way down, the branch condition gives me two branches at each step: take the current element or skip it. Once I've considered all the elements, I've reached the termination condition and can return.


Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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):
self.results = [ ] # start fresh on every call, the same object may be reused
S.sort()
self.doSubsets(S, [ ], 0)
return self.results

Article link: https://xnerv.wang/en/leetcode-subsets/