C# iterate 0 thru 2^n include index if bit is a 1 (same as others)


  • 0
    public IList<IList<int>> Subsets(int[] nums) {
        IList<IList<int>> set = new List<IList<int>>();
        int n = nums.Length;
        int max = 1;
        for (int i = 0; i < n; i++) max = max << 1;
        
        for (int i = 0; i < max; i++)
        {
            int mask = 1;
            IList<int> sub = new List<int>();
            for (int b = 0; b < n; b++)
            {
                if ((mask & i) != 0)
                {
                    sub.Add(nums[b]);
                }
                
                mask = mask << 1;
            }
            set.Add(sub);
        }
        
        return set;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.