LeetCode: Subsets II (binary manipulation for subsets of a set)
https://leetcode.com/problems/subsets-ii/ , problem statement: Given a collection of integers that might contain duplicates, nums , return all possible subsets. 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], [] ] I've posted before a trick to generate subsets of a set non-recursively by using bit math, you can read the post here: https://anothercasualcoder.blogspot.com/2014/10/a-non-recursive-trick-for-subsets.html . Technique to solve this problem is exactly the same with two caveats: First sort the input array so that the key generation for the hash table becomes unique Then keep track of the solutions already seen using a hash table Complexity is still O(2^n) (actually nlog + 2^n). Beats more than half of the C# submissions. Code is down below, cheers, Marcelo. Code: public class Solution ...