classSolution{List<Integer> t =newArrayList<>();List<List<Integer>> ans =newArrayList<>();publicList<List<Integer>>subsets(int[] nums){int n = nums.length;for(int mask =0; mask <(1<< n);++mask){
t.clear();for(int i =0; i < n;++i){if((mask &(1<< i))!=0){
t.add(nums[i]);}}
ans.add(newArrayList<>(t));}return ans;}}
方法二:递归法实现子集枚举
classSolution{publicList<List<Integer>>subsets(int[] nums){List<List<Integer>> ans =newArrayList<>();if(nums ==null){return ans;}dfs(ans, nums,newArrayList<Integer>(),0);return ans;}privatevoiddfs(List<List<Integer>> ans,int[] nums,List<Integer> list,int index){//terminatorif(index == nums.length){
ans.add(newArrayList<Integer>(list));return;}dfs(ans, nums, list, index +1);//not pick the number at this index;
list.add(nums[index]);dfs(ans, nums, list, index +1);//pick the number at this index//reverse the current state
list.remove(list.size()-1);}}classSolution{List<Integer> t =newArrayList<Integer>();List<List<Integer>> ans =newArrayList<List<Integer>>();publicList<List<Integer>>subsets(int[] nums){dfs(0, nums);return ans;}publicvoiddfs(int cur,int[] nums){if(cur == nums.length){
ans.add(newArrayList<Integer>(t));return;}
t.add(nums[cur]);dfs(cur +1, nums);
t.remove(t.size()-1);dfs(cur +1, nums);}}