- 题目
给定一组不同的整数 nums,返回所有可能的子集(幂集)。注意事项:该解决方案集不能包含重复的子集。
![这里写图片描述](https://i-blog.csdnimg.cn/blog_migrate/e89229e5e21f7efdf9b914a829838cf7.jpeg)
- 思路
1.设置一个大机器人robot解决主问题,对于全排列的每一个元素index,都有取index和不取index区别
2.设置一个辅助数组v[],来记录当前index是取还是不取。
3.当前元素取,执行小机器人robot对下一个元素进行判断
4.当前元素不取,执行小机器人robot对下一个元素进行判断
5.直到小机器人遍历完数组,将当前的组合情况放入List。
class Solution {
public static boolean[] v = new boolean[100];
public static List<List<Integer>> ans = new ArrayList<List<Integer>>();
public void robot(int index, int[] nums){
if(index >= nums.length){
List<Integer> r = new ArrayList<Integer>();
for(int i = 0; i < nums.length; i++){
if(v[i]){
r.add(nums[i]);
}
}
ans.add(r);
return;
}
v[index] = true;
robot(index + 1, nums);
v[index] = false;
robot(index + 1, nums);
}
public List<List<Integer>> subsets(int[] nums) {
ans.clear();
robot(0, nums);
return ans;
}
}