C# recursive approach


  • 0
    B

    public IList<IList<int>> Subsets(int[] nums) {

        IList<IList<int>> result = new List<IList<int>>();
        if(nums == null || nums.Length == 0)
            return result;
        Array.Sort(nums);
        List<int> subset = new List<int>();
        SubsetUtil(nums, nums.Length, subset, 0, result);
        result.Add(new List<int>());
        return result;
    }
    
    private void SubsetUtil(int[] nums, int maxLen,  List<int> subset, int start, IList<IList<int>> res)
    {
        for(int i = start ; i < maxLen; i++)
        {
            subset.Add(nums[i]);
            res.Add(new List<int>(subset));
            SubsetUtil(nums, maxLen, subset, i + 1, res);
            subset.RemoveAt(subset.Count - 1);
        }
        
    }

Log in to reply
 

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