78. Subsets | & ||

Subsets I

Given a set of distinct integers, return all possible subsets.

 Notice
  • Elements in a subset must be in non-descending order.
  • The solution set must not contain duplicate subsets.
Example

If S = [1,2,3], a solution is:

[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]
 1 class Solution {
 2   public List<List<Integer>> subsets(int[] nums) {
 3       if (nums == null) return null;
 4       List<List<Integer>> allList = new LinkedList<>();
 5       LinkedList<Integer> list = new LinkedList<>();
 6         allList.add(new LinkedList<>());
 7         helper(allList, list, nums, 0);
 8         return allList;
 9   }
10   private void helper(List<List<Integer>> allList, LinkedList<Integer> list, int[] nums, int index) {
11       if (index >= nums.length) return;
12       
13       list.add(nums[index]);
14       allList.add(new LinkedList<>(list));
15       helper(allList, list, nums, index + 1);
16       list.removeLast();
17       helper(allList, list, nums, index + 1);
18   }
19 }

Subsets II

Given a list of numbers that may has duplicate numbers, return all possible subsets

 Notice
  • Each element in a subset must be in non-descending order.
  • The ordering between two subsets is free.
  • The solution set must not contain duplicate subsets.
Example

If S = [1,2,2], a solution is:

[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]
 1 class Solution {
 2   public List<List<Integer>> subsetsWithDup(int[] nums) {
 3       if (nums == null) return null;
 4       Arrays.sort(nums);
 5       List<List<Integer>> allList = new LinkedList<>();
 6       LinkedList<Integer> list = new LinkedList<>();
 7         allList.add(new LinkedList<>());
 8         helper(allList, list, nums, 0);
 9         return allList;
10   }
11   private void helper(List<List<Integer>> allList, LinkedList<Integer> list, int[] nums, int index) {
12       if (index >= nums.length) return;
13       
14       list.add(nums[index]);
15       allList.add(new LinkedList<>(list));
16       helper(allList, list, nums, index + 1);
17       list.removeLast();
18       while (index + 1 < nums.length && nums[index] == nums[index + 1]) {
19         index++;
20       }
21       helper(allList, list, nums, index + 1);
22   }
23 }

转载请注明出处: cnblogs.com/beiyeqingteng/
posted @ 2014-12-31 11:24  北叶青藤  阅读(354)  评论(0)    收藏  举报