Question
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],
[]
]
Code
递归
public List<List<Integer>> subsets1(int[] S) {
List<List<Integer>> ret = new ArrayList<List<Integer>>();
if (S == null) {
return ret;
}
Arrays.sort(S);
dfs(S, 0, new ArrayList<Integer>(), ret);
return ret;
}
public void dfs(int[] S, int index, List<Integer> path, List<List<Integer>> ret) {
ret.add(new ArrayList<Integer>(path));
for (int i = index; i < S.length; i++) {
path.add(S[i]);
dfs(S, i + 1, path, ret);
path.remove(path.size() - 1);
}
}
位运算方式
public List<List<Integer>> subsets(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> results = new ArrayList<>();
int len = (int) Math.pow(2, nums.length);
boolean[] flags = new boolean[nums.length];
for (int i = 0; i < len; i++) {
for (int j = 0; j < flags.length; j++) {
if (!flags[j]) {
flags[j] = true;
break;
}
flags[j] = false;
}
List<Integer> sub = new ArrayList<>();
for (int j = 0; j < flags.length; j++) {
if (flags[j]) {
sub.add(nums[j]);
}
}
results.add(sub);
}
return results;
}