Subsets
2015-01-08 12:51
239 查看
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 =
Analysis:
There are two ways to think about it.
first: each element in S could be selected or not selected. we can use recursion.
second: for n.th element, the number of subsets is twice as large as that of subsets created by first n-1 elements. we can use recursion or iteration.
Summary:
get the deeper understanding of recursion and iteration. For iteration, it is usual that there is a for loop in it. For recursion, we only have one function to enter the process and another function will call itself many times. Sometimes, there is a internal
variable pass through all iterative funcitons.
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], [] ]
Analysis:
There are two ways to think about it.
first: each element in S could be selected or not selected. we can use recursion.
second: for n.th element, the number of subsets is twice as large as that of subsets created by first n-1 elements. we can use recursion or iteration.
class Solution: # @param S, a list of integer # @return a list of lists of integer ## wu ## recursive def subsets(self, S): if len(S)==0: return [[]] res = [[]] S = sorted(S) for elem in S: newres = [] for elemres in res: new = elemres[:] new.append(elem) newres.append(new) res = res + newresHTere return res
Summary:
get the deeper understanding of recursion and iteration. For iteration, it is usual that there is a for loop in it. For recursion, we only have one function to enter the process and another function will call itself many times. Sometimes, there is a internal
variable pass through all iterative funcitons.
相关文章推荐
- LeetCode(78) Subsets
- 使用位运算解决subsets
- LeetCode Subsets II (DFS)
- Subsets 子集系列问题 leetcode
- P27 (**) Group the elements of a set into disjoint subsets.
- lintcode:Subsets
- leetcode 078 subsets
- 【Leetcode】之Subsets
- Subsets
- LeetCode 78 Subsets (DFS 或 状态压缩)
- *[Lintcode]Subsets 子集
- Subsets
- [LeetCode] 78. Subsets
- Subsets & Subsets II
- LeetCode:Subsets
- BZOJ 2679: [Usaco2012 Open]Balanced Cow Subsets meet_in_the_middle / 折半搜索
- 【BZOJ】2679: [Usaco2012 Open]Balanced Cow Subsets
- A general approach to backtracking questions in Java (Subsets, Permutations, Combination Sum, Palind
- ???Frequent Subsets Problem
- 698. Partition to K Equal Sum Subsets(M)