1. 程式人生 > >Leetcode 90: Subsets II

Leetcode 90: Subsets II

note pre sub cti esc sta private ++ dfs

Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

For example,
If nums = [1,2,2], a solution is:

[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]

 1 public class Solution {
2 public IList<IList<int>> SubsetsWithDup(int[] nums) { 3 var results = new List<IList<int>>(); 4 5 if (nums.Length == 0) return results; 6 7 Array.Sort(nums); 8 results.Add(new List<int>()); 9 DFS(nums, 0
, new List<int>(), results); 10 return results; 11 } 12 13 private void DFS(int[] nums, int start, IList<int> result, IList<IList<int>> results) 14 { 15 for (int i = start; i < nums.Length; i++) 16 { 17 if (i == start || nums[i] != nums[i - 1
]) 18 { 19 result.Add(nums[i]); 20 results.Add(new List<int>(result)); 21 DFS(nums, i + 1, result, results); 22 result.RemoveAt(result.Count - 1); 23 } 24 } 25 } 26 }

Leetcode 90: Subsets II