题目:
给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
说明:解集不能包含重复的子集。
示例:
输入: nums = [1,2,3]
输出:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
思路:
1、先前都是使用 path[ ] 数组来记录子结果集,但是在本题中,每一个子结果集的长度并不古蒂昂,所以在record ans 的时候并不好操作
2、所以改用一个boolean数组来记录某一下标的元素是否被选中
3、同时,roboot方法中也不需要 for 循环来挨个确定path中每一位结果的下标了,因为只会有两种情况:
选中idx上的这个数,或者不选idx上的这个数
代码:
class Solution {
public static List<List<Integer>> ans = new ArrayList<List<Integer>>();
//因为搜完之后并不知道子集合有多少个元素,所以用path有点不合适
//用一个boolean数组来判断某一数字选没选过
public static boolean[] v = new boolean[100];
public void roboot(int idx, int[] nums) {
if (idx >= nums.length) {
//record ans
List<Integer> temp = new ArrayList<Integer>();
for (int i = 0; i <= nums.length; i++) {
if (v[i])
temp.add(nums[i]);
}
ans.add(temp);
return;
}
//两种情况:idx取、不取
v[idx] = true;
roboot(idx + 1, nums);
v[idx] = false;
roboot(idx + 1, nums);
}
public List<List<Integer>> subsets(int[] nums) {
ans.clear();
//先把数组排序
Arrays.sort(nums);
roboot(0, nums);
return ans;
}
}