Subsets (M)
Given a set of distinct integers, nums, return all possible subsets (the power set).
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],
[]
]
题意
求一个数组的幂集(即所有子集,包括全集和空集,构成的集族)。
思路
回溯法。
也可以利用位运算来求子集,具体方法参考 LeetCode 78. Subsets (位运算入门:利用位运算求子集)。
代码实现 - 回溯法
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> ans = new ArrayList<>();
subsets(nums, 0, new ArrayList<>(), ans);
return ans;
}
private void subsets(int[] nums, int index, List<Integer> list, List<List<Integer>> ans) {
if (index == nums.length) {
ans.add(new ArrayList<>(list));
return;
}
subsets(nums, index + 1, list, ans);
list.add(nums[index]);
subsets(nums, index + 1, list, ans);
list.remove(list.size() - 1);
}
}
代码实现 - 位运算
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> ans = new ArrayList<>();
List<Integer> list = new ArrayList<>();
int all = 1 << (nums.length); // 总情况数
for (int i = 0; i < all; i++) {
// 判断数组中每一个数是否应该添加
for (int j = 0; j < nums.length; j++) {
if ((i & (1 << j)) > 0) {
list.add(nums[j]);
}
}
ans.add(new ArrayList<>(list));
list.clear();
}
return ans;
}
}
本文深入探讨了求解数组幂集(所有可能的子集)的两种算法:回溯法和位运算法。通过实例说明了如何使用这两种方法求得一个整数数组的所有子集,包括详细的代码实现。
318

被折叠的 条评论
为什么被折叠?



