Subsets
Given a set of distinct integers, nums, return all possible subsets (the power set). [#78]
Note: The solution set must not contain duplicate subsets.
Example: Input: nums = [1,2,3] Output: [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
这与之前经常用的子序列不同,本题要求的子序列的元素可以是原序列中的非连续相邻元素:
>>> def subsets(lst): ret = [[]] for n in lst: for r in ret[:]: t=r[:] t.append(n) ret.append(t) return ret >>> subsets([1,2,3]) [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]] >>> subsets([1,2,2,3]) [[], [1], [2], [1, 2], [2], [1, 2], [2, 2], [1, 2, 2], [3], [1, 3], [2, 3], [1, 2, 3], [2, 3], [1, 2, 3], [2, 2, 3], [1, 2, 2, 3]] >>>
若要求的是连续元素的子序列:
>>> subsets = lambda s:[s[i:j] for i in range(len(s)) for j in range(i+1,len(s)+1)]+[[]] >>> subsets([1,2,3]) [[1], [1, 2], [1, 2, 3], [2], [2, 3], [3], []] >>> >>> # 去重操作: >>> lst = [1,2,2,3] >>> subsets(lst) [[1], [1, 2], [1, 2, 2], [1, 2, 2, 3], [2], [2, 2], [2, 2, 3], [2], [2, 3], [3], []] >>> result = [] >>> [result.append(i) for i in subsets(lst) if i not in result] [None, None, None, None, None, None, None, None, None, None] >>> result [[1], [1, 2], [1, 2, 2], [1, 2, 2, 3], [2], [2, 2], [2, 2, 3], [2, 3], [3], []] >>>
自定义函数:
>>> def subsets(lst): res, t = [], [[]] lenth = len(lst) for i in range(lenth): for j in range(i+1,lenth+1): t.append(lst[i:j]) for i in t: if i not in res: res.append(i) return res >>> subsets([1,2,3]) [[], [1], [1, 2], [1, 2, 3], [2], [2, 3], [3]] >>> subsets([1,2,2,3]) [[], [1], [1, 2], [1, 2, 2], [1, 2, 2, 3], [2], [2, 2], [2, 2, 3], [2, 3], [3]] >>>
Subsets II
Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set). [#90]
Note: The solution set must not contain duplicate subsets.
Example: Input: [1,2,2] Output: [ [2], [1], [1,2,2], [2,2], [1,2], [] ]