给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
说明:解集不能包含重复的子集。
示例:
输入: nums = [1,2,3] 输出: [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
两种做法,一种递归,一种递推
做法一(递归):
class Solution {
boolean v[]=new boolean[100];
int input[];
int len;
List<List<Integer>> res=new ArrayList<>();
public void solution(int index){
if(index>=len){
List<Integer>item = new ArrayList<>();
for(int i=0;i<len;i++){
if(v[i]){
item.add(input[i]);
}
}
res.add(item);
return;
}
v[index]=true;
solution(index+1);
v[index]=false;
solution(index+1);
}
public List<List<Integer>> subsets(int[] nums) {
input=nums;
len=input.length;
solution(0);
return res;
}
}
做法二(递推):
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> list1 = new ArrayList<List<Integer>>();
list1.add(new ArrayList<Integer>());
for(int num:nums){
int size=list1.size(); //必须定义在内循环前
for(int j=0;j<size;j++){
List<Integer> temp = new ArrayList<>(list1.get(j));
temp.add(num);
list1.add(temp);
}
}
return list1;
}
}