冪集。編寫一種方法,返回某集合的所有子集。集合中不包含重復的元素。
說明:解集不能包含重復的子集。
示例:
輸入: nums = [1,2,3]
輸出:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
代碼
class Solution {List<List<Integer>> ress=new ArrayList<>();public List<List<Integer>> subsets(int[] nums) {sub(nums,0);
return ress;}public void sub(int[] nums,int loc) {List<List<Integer>> ss=new ArrayList<>();if(loc==nums.length)//遞歸邊界{ress.add(new ArrayList<>());return ;}sub(nums, loc+1);List<List<Integer>> next=new ArrayList<>(ress);for(List<Integer> l:ress)//將后面的子集和當前的連接{ArrayList<Integer> na=new ArrayList<>(l);na.add(nums[loc]);next.add(new ArrayList<>(na));}ress=next;//刷新子集結果}
}