0~n-1的子集:不重复的顺序子集 给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
import java.util.*;public class { public List<List<Integer>> subsets(int [] nums) { List<List<Integer>> res = new ArrayList<>(); for (int mask = 0 ; mask < (1 << nums.length); mask++) { List<Integer> tmp = new ArrayList<>(); for (int i=0 ; i < nums.length; i++) { if ( ((mask >> i) & 1 ) == 1 ) { tmp.add(nums[i]); } } res.add(tmp); } return res; } List<List<Integer>> res; int mark[] ; public List<List<Integer>> subsets_recur(int [] nums) { if (nums==null || nums.length==0 ) return null ; res = new ArrayList<>(); mark = new int [nums.length]; dfs(nums,0 ); return res; } public void dfs (int [] nums, int pos) { if (pos == nums.length) { ArrayList<Integer> tmp = new ArrayList<>(); for (int i = 0 ; i< nums.length; i++) { if (mark[i] == 1 ) { tmp.add(nums[i]); } } res.add(tmp); return ; } mark[pos] = 1 ; dfs(nums,pos+1 ); mark[pos] = 0 ; dfs(nums,pos+1 ); } public static void main (String[] args) { int [] nums = {1 ,2 ,3 }; } }
近期评论