Subsets - Array - Medium - LeetCode
💻 coding

Subsets - Array - Medium - LeetCode

1 min read 112 words
1 min read
ShareWhatsAppPost on X
  • 1The task is to generate all possible subsets from a set of distinct integers without duplicates.
  • 2The provided solution uses recursion to build subsets and ensures no duplicates through checks.
  • 3The time complexity of the algorithm is O(2^n) and the space complexity is O(n) for stack trace.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The task is to generate all possible subsets from a set of distinct integers without duplicates."

Subsets - Array - Medium - LeetCode

Given a set of distinct integers, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example:

Input: nums = [1,2,3] Output: [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]

public class Solution {
 IList<IList<int>> res = new List<IList<int>>(); 
 public IList<IList<int>> Subsets(int[] nums) {
 Array.Sort(nums);
 res.Add(new List<int>());
 var ans = new List<int>(); 
 Helper(nums,ans, 0);
 return res;
 }
 
 private void Helper(int[] nums, List<int> ans, int index){
 if(ans.Count() > nums.Length){
 return;
 }
 
 if(ans.Count()>0){
 CheckAndAdd(ans);
 }
 
 for(int i=index;i< nums.Length;i++){
 if(ans.Contains(nums[i])){
 continue;
 }
 ans.Add(nums[i]);
 Helper(nums, ans, i+1);
 ans.RemoveAt(ans.Count()-1);
 }
 }
 
 private void CheckAndAdd(List<int> ans){
 res.Add(ans.ToArray().ToList()); 
 }
}

Time Complexity: O(2^n)

Space Complexity: O(n) // for stack trace

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 31 October 2020 · 1 min read · 112 words

Part of AskGif Blog · coding

You might also like

Subsets - Array - Medium - LeetCode | AskGif Blog