# [刷题]Subsets

[LintCode]Subsets

Version I

class Solution {
/**
* @param S: A set of numbers.
* @return: A list of lists. All valid subsets.
*/
public ArrayList<ArrayList<Integer>> subsets(ArrayList<Integer> S) {
// 2015-07-07
ArrayList<ArrayList<Integer>> rst = new ArrayList<>();
if (S == null) {
return rst;
}
ArrayList<Integer> list = new ArrayList<>();

helper(rst, list, S);
return rst;
}

private void helper(ArrayList<ArrayList<Integer>> rst,
ArrayList<Integer>list, ArrayList<Integer> S) {
// 树的深度
// if (list.size() == S.size()) {
//     return;
// }

for (int i = 0; i < S.size(); i++) {
if (list.size() > 0 && list.get(list.size() - 1) >= S.get(i)) {
continue;
}
helper(rst, list, S);
list.remove(list.size() - 1);
}
return;
}
}


Version II

class Solution {
/**
* @param S: A set of numbers.
* @return: A list of lists. All valid subsets.
*/
public ArrayList<ArrayList<Integer>> subsets(ArrayList<Integer> S) {
// 2015-08-28
// S中不含相同元素，每个元素只可以用一次
// 解集中不可以含相同解
// 因此 解中不会含相同元素
ArrayList<ArrayList<Integer>> rst = new ArrayList<>();
if (S == null || S.size() == 0) {
return rst;
}
Collections.sort(S);
ArrayList<Integer> list = new ArrayList<>();
helper(S, rst, list, 0);
return rst;

}

private void helper(ArrayList<Integer> S, ArrayList<ArrayList<Integer>> rst,
ArrayList<Integer> list, int pos) {
// if (pos == S.size()) {
//     return;
// }
for (int i = pos; i < S.size(); i++) {
helper(S, rst, list, i + 1);
list.remove(list.size() - 1);
}
}
}

• 本文已收录于以下专栏：

## Leetcode刷题系列（一）Subsets 与 Permutation

Leetcode刷题系列（一）Subsets 与 Permutation　　这两种题型如果用Recursion的方法来解决，其思路是及其相似的。1.Subsets I内容Given a set of ...

## Subsets

Given a set of distinct integers, S, return all possible subsets. Note: Elements in a subset must...

## Leetcode : Subsets II

URL：https://leetcode.com/problems/subsets-ii/#/description题目大意：Given a collection of integers that m...

## leetcode 90. Subsets II

Given a collection of integers that might contain duplicates, nums, return all possible subsets. ...

## 【leetcode】90. Subsets II

leetcode, subsets ||， 3种解法

## leetcode：暴力枚举法之Subsets II

leetcode：暴力枚举法之Subsets II 题目; Given a collection of integers that might contain duplicates, S, retur...

## LeetCode OJ:Subsets II

Subsets II   Given a collection of integers that might contain duplicates, S, return all possible...

举报原因： 您举报文章：深度学习：神经网络中的前向传播和反向传播算法推导 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)