Subset
给定一个集合,求出这个集合的所有子集,该子集不包含重复元素
-
递归
public List<List
> subsets(int[] s) { Arrays.sort(S); List<List > result = new ArrayList<List >(); List tmp = new ArrayList<>(); res.add(tmp); }
public void helper(int[] S, int index, List<List
> result, List temp) { if (index >= S.length) { return; } helper(S, index + 1, result, temp); List temp2 = new ArrayList<>(temp); temp2.add(S[index]); result.add(temp2); helper(S, index + 1, result, temp2); }
-
非递归
public List<List
> subsets(int[] nums) { if (nums == null || 0 == nums.length) return null; List<List<Integer>> result = new ArrayList<List<Integer>>(); result.add( new ArrayList<Integer>() ); Arrays.sort(nums); for (int num : nums) { List<List<Integer>> tmp = new ArrayList<List<Integer>>(); for (List<Integer> sub : result) { List<Integer> another_temp = new ArrayList<Integer>(sub); another_temp.add(num); tmp.add(another_temp); } result.addAll(tmp); } return result; }
-
利用位
Written on September 7, 2018