Given a set of distinct integers, nums, return all possible subsets.
Note: 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], [] ]
题目链接:https://leetcode.com/problems/subsets/
题目分析:一个包含n个元素的集合的子集共有2^n - 1个
DFS:对每一位有选和不选两种情况
public class Solution {
public void DFS (int pos, int len, int[] nums, List<Integer> tmp, List<List<Integer>> ans) {
if (pos == len) {
ans.add(new ArrayList<>(tmp));
return;
}
tmp.add(nums[pos]);
DFS(pos + 1, len, nums, tmp, ans);
tmp.remove(tmp.size() - 1);
DFS(pos + 1, len, nums, tmp, ans);
}
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> ans = new ArrayList<>();
List<Integer> tmp = new ArrayList<>();
int len = nums.length;
DFS(0, len, nums, tmp, ans);
return ans;
}
}
状态压缩:枚举所有情况
public class Solution {
public List<List<Integer>> subsets(int[] nums) {
int sz = nums.length;
int all = (1 << sz);
List<List<Integer>> ans = new ArrayList<>();
List<Integer> tmp = new ArrayList<>();
ans.add(tmp);
for (int i = 1; i < all; i ++) {
tmp = new ArrayList<>();
for (int j = 0; j < 31; j ++) {
if (((1 << j) & i) != 0) {
tmp.add(nums[j]);
}
}
ans.add(tmp);
}
return ans;
}
}