题目
分析
1、对于数组S中每个元素有两种选择,要么选入子集,要么不选入子集,因此可以用比特位表示对应元素是否被选中,如{1,2,3},其对应的情况是000-111(0表示不选中,1表示选中)
import java.util.*;
public class Solution {
public ArrayList<ArrayList<Integer>> subsets(int[] S) {
//对数组进行排序
Arrays.sort(S);
//返回的数组
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
for(int i = 0; i <= Math.pow(2,S.length)-1; i++) {
ArrayList<Integer> list = new ArrayList<>();
int m = i;
for(int j = S.length-1; j >= 0; j--) {
if((m & 1) == 1) {
list.add(0,S[j]);
}
m = m >> 1;
}
res.add(list);
}
return res;
}
}
2、回溯,以{1,2,3}为例,其对应的回溯的树形结构如下图:
每次添加一个新的元素到路径中,其就构成一个新的子集。
import java.util.*;
public class Solution {
public ArrayList<ArrayList<Integer>> subsets(int[] S) {
//对数组进行排序
Arrays.sort(S);
//返回的数组
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
ArrayList<Integer> list = new ArrayList<>();
helper(S,0,res,list);
return res;
}
public void helper(int[] S,int begin,ArrayList<ArrayList<Integer>> res,ArrayList<Integer> list) {
res.add(new ArrayList<>(list));
for (int i = begin; i < S.length; i++) {
list.add(S[i]);
helper(S,i + 1,res,list);
list.remove(list.size()-1);
}
}
}