add subsets

This commit is contained in:
Evan Ferrao 2026-02-05 14:51:38 +05:30 committed by GitHub
parent fa996714d1
commit 2440656782
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 93 additions and 0 deletions

42
Recursion/Subset.java Normal file
View File

@ -0,0 +1,42 @@
import java.util.*;
public class Subset {
public static void printSubset(int currentIndex, List<Integer> ds, int[] nums, int n, List<List<Integer>> finalAnswer){
if (currentIndex == n){
finalAnswer.add(new ArrayList<>(ds));
return;
}
ds.add(nums[currentIndex]);
printSubset(currentIndex + 1, ds, nums, n, finalAnswer);
ds.remove(ds.size() - 1);
printSubset(currentIndex + 1, ds, nums, n, finalAnswer);
}
public List<List<Integer>> subsets(int[] nums) {
int n = nums.length;
List<Integer> ds = new ArrayList<>();
List<List<Integer>> finalAnswer = new ArrayList<>();
printSubset(0, ds, nums, n, finalAnswer);
return finalAnswer;
}
// -------- DRIVER CODE --------
public static void main(String[] args) {
// Assumed Input
int[] nums = {1, 2, 3};
Solution sol = new Solution();
List<List<Integer>> result = sol.subsets(nums);
System.out.println("Subsets:");
for (List<Integer> subset : result) {
System.out.println(subset);
}
}
}

View File

@ -0,0 +1,51 @@
import java.util.*;
class SubsetsWithoutDuplicates {
public static void printSubset(int currentIndex, List<Integer> ds, int[] nums, int n, List<List<Integer>> finalAnswer){
if (currentIndex == n){
finalAnswer.add(new ArrayList<>(ds));
return;
}
// Include
ds.add(nums[currentIndex]);
printSubset(currentIndex + 1, ds, nums, n, finalAnswer);
ds.remove(ds.size() - 1);
// Exclude
int nextIndex = currentIndex + 1;
while (nextIndex < n && nums[nextIndex] == nums[currentIndex]){
nextIndex++;
}
printSubset(nextIndex, ds, nums, n, finalAnswer);
}
public List<List<Integer>> subsetsWithDup(int[] nums) {
Arrays.sort(nums);
int n = nums.length;
List<Integer> ds = new ArrayList<Integer>();
List<List<Integer>> finalAnswer = new ArrayList<>();
printSubset(0, ds, nums, n, finalAnswer);
return finalAnswer;
}
}
public class Main {
public static void main(String[] args) {
// Assumed Test Input
int[] nums = {1, 2, 2};
Solution sol = new Solution();
List<List<Integer>> result = sol.subsetsWithDup(nums);
System.out.println("Subsets Without Duplicates:");
for (List<Integer> subset : result) {
System.out.println(subset);
}
}
}