给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。
解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。
示例 1:
输入:nums = [1,2,3] 输出:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
示例 2:
输入:nums = [0] 输出:[[],[0]]
提示:
1 <= nums.length <= 10-10 <= nums[i] <= 10nums 中的所有元素 互不相同1 class Solution { 2 public static List<List<Integer>> list; 3 public static List<Integer> alist; 4 5 public List<List<Integer>> subsets(int[] nums) { 6 7 list=new ArrayList<>(); 8 alist=new ArrayList<>(); 9 10 list.add(new ArrayList<>()); 11 12 13 for (int i = 1; i <= nums.length; i++) { 14 alist.clear(); 15 backTrack(nums.length,i,0,0,nums); 16 } 17 18 return list; 19 } 20 21 //size记录目前alist的长度,t代表目前走到的数组下标 ,size==k时存入list中 22 public static void backTrack(int n, int k,int t,int size,int[] nums){ 23 if(size>=k){ 24 list.add(new ArrayList<>(alist)); 25 }else{ 26 for (int i = t; i < n; i++) { 27 28 if(size+1<=k){ 29 alist.add(nums[i]); 30 backTrack(n,k,i+1,size+1,nums); 31 alist.remove(new Integer(nums[i])); 32 } 33 } 34 } 35 } 36 }

原文:https://www.cnblogs.com/SEU-ZCY/p/14774661.html